Skip to content

Commit

Permalink
Clarify extension method access (#42808)
Browse files Browse the repository at this point in the history
* Clarify extension method declaration

Extension methods can only be declared in top-level type. They can't be declared in nested types.

* quick formatting fix

* fix a snippet issue

* one more time
  • Loading branch information
BillWagner authored Oct 2, 2024
1 parent 6673ac7 commit 3ce2e97
Show file tree
Hide file tree
Showing 5 changed files with 86 additions and 94 deletions.
Original file line number Diff line number Diff line change
@@ -1,42 +1,33 @@
---
title: "How to implement and call a custom extension method"
description: Learn how to implement extension methods for any .NET type. Client code can use your methods by adding a reference to a DLL and adding a using directive.
ms.date: 07/20/2015
ms.date: 10/02/2024
helpviewer_keywords:
- "extension methods [C#], implementing and calling"
ms.topic: how-to
ms.assetid: 7dab2a56-cf8e-4a47-a444-fe610a02772a
---
# How to implement and call a custom extension method (C# Programming Guide)

This topic shows how to implement your own extension methods for any .NET type. Client code can use your extension methods by adding a reference to the DLL that contains them, and adding a [using](../../language-reference/keywords/using-directive.md) directive that specifies the namespace in which the extension methods are defined.

## To define and call the extension method

1. Define a static [class](./static-classes-and-static-class-members.md) to contain the extension method.

The class must be visible to client code. For more information about accessibility rules, see [Access Modifiers](./access-modifiers.md).

2. Implement the extension method as a static method with at least the same visibility as the containing class.

3. The first parameter of the method specifies the type that the method operates on; it must be preceded with the [this](../../language-reference/keywords/this.md) modifier.

4. In the calling code, add a `using` directive to specify the [namespace](../../language-reference/keywords/namespace.md) that contains the extension method class.

5. Call the methods as if they were instance methods on the type.

Note that the first parameter is not specified by calling code because it represents the type on which the operator is being applied, and the compiler already knows the type of your object. You only have to provide arguments for parameters 2 through `n`.

## Example

The following example implements an extension method named `WordCount` in the `CustomExtensions.StringExtension` class. The method operates on the <xref:System.String> class, which is specified as the first method parameter. The `CustomExtensions` namespace is imported into the application namespace, and the method is called inside the `Main` method.

[!code-csharp[csProgGuideExtensionMethods#1](~/samples/snippets/csharp/VS_Snippets_VBCSharp/csProgGuideExtensionMethods/cs/extensionmethods.cs#1)]

## .NET Security

Extension methods present no specific security vulnerabilities. They can never be used to impersonate existing methods on a type, because all name collisions are resolved in favor of the instance or static method defined by the type itself. Extension methods cannot access any private data in the extended class.

This article shows how to implement your own extension methods for any .NET type. Client code can use your extension methods. Client projects must reference the assembly that contains them. Client projects must add a [using](../../language-reference/keywords/using-directive.md) directive that specifies the namespace in which the extension methods are defined.

To define and call the extension method:

1. Define a static [class](./static-classes-and-static-class-members.md) to contain the extension method. The class can't be nested inside another type and must be visible to client code. For more information about accessibility rules, see [Access Modifiers](./access-modifiers.md).
1. Implement the extension method as a static method with at least the same visibility as the containing class.
1. The first parameter of the method specifies the type that the method operates on; it must be preceded with the [this](../../language-reference/keywords/this.md) modifier.
1. In the calling code, add a `using` directive to specify the [namespace](../../language-reference/keywords/namespace.md) that contains the extension method class.
1. Call the methods as instance methods on the type.

> [!NOTE]
>
> The first parameter is not specified by calling code because it represents the type on which the operator is being applied, and the compiler already knows the type of your object. You only have to provide arguments for parameters 2 through `n`.
The following example implements an extension method named `WordCount` in the `CustomExtensions.StringExtension` class. The method operates on the <xref:System.String> class, which is specified as the first method parameter. The `CustomExtensions` namespace is imported into the application namespace, and the method is called inside the `Main` method.

:::code language="csharp" source="./snippets/how-to-implement-and-call-a-custom-extension-method/Program.cs" :::

Overload resolution prefers instance or static method defined by the type itself to extension methods. Extension methods can't access any private data in the extended class.

## See also

- [Extension Methods](./extension-methods.md)
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
using CustomExtensions;

string s = "The quick brown fox jumped over the lazy dog.";
// Call the method as if it were an
// instance method on the type. Note that the first
// parameter is not specified by the calling code.
int i = s.WordCount();
System.Console.WriteLine("Word count of s is {0}", i);


namespace CustomExtensions
{
// Extension methods must be defined in a static class.
public static class StringExtension
{
// This is the extension method.
// The first parameter takes the "this" modifier
// and specifies the type for which the method is defined.
public static int WordCount(this string str)
{
return str.Split(new char[] {' ', '.','?'}, StringSplitOptions.RemoveEmptyEntries).Length;
}
}
}

Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
<Project Sdk="Microsoft.NET.Sdk">

<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net9.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
</PropertyGroup>

</Project>
Original file line number Diff line number Diff line change
@@ -1,38 +1,4 @@
//<Snippet1>
namespace CustomExtensions
{
// Extension methods must be defined in a static class.
public static class StringExtension
{
// This is the extension method.
// The first parameter takes the "this" modifier
// and specifies the type for which the method is defined.
public static int WordCount(this string str)
{
return str.Split(new char[] {' ', '.','?'}, StringSplitOptions.RemoveEmptyEntries).Length;
}
}
}
namespace Extension_Methods_Simple
{
// Import the extension method namespace.
using CustomExtensions;
class Program
{
static void Main(string[] args)
{
string s = "The quick brown fox jumped over the lazy dog.";
// Call the method as if it were an
// instance method on the type. Note that the first
// parameter is not specified by the calling code.
int i = s.WordCount();
System.Console.WriteLine("Word count of s is {0}", i);
}
}
}
//</Snippet1>

namespace Extension2
namespace Extension2
{

//<snippet2>
Expand All @@ -42,40 +8,40 @@ namespace EnumExtension
{
// Define an extension method in a non-nested static class.
public static class Extensions
{
public static Grades minPassing = Grades.D;
public static bool Passing(this Grades grade)
{
return grade >= minPassing;
public static Grades minPassing = Grades.D;
public static bool Passing(this Grades grade)
{
return grade >= minPassing;
}
}
}

public enum Grades { F = 0, D=1, C=2, B=3, A=4 };
class Program
{
static void Main(string[] args)
public enum Grades { F = 0, D=1, C=2, B=3, A=4 };
class Program
{
Grades g1 = Grades.D;
Grades g2 = Grades.F;
Console.WriteLine("First {0} a passing grade.", g1.Passing() ? "is" : "is not");
Console.WriteLine("Second {0} a passing grade.", g2.Passing() ? "is" : "is not");

Extensions.minPassing = Grades.C;
Console.WriteLine("\r\nRaising the bar!\r\n");
Console.WriteLine("First {0} a passing grade.", g1.Passing() ? "is" : "is not");
Console.WriteLine("Second {0} a passing grade.", g2.Passing() ? "is" : "is not");
}
}
}
/* Output:
First is a passing grade.
Second is not a passing grade.
static void Main(string[] args)
{
Grades g1 = Grades.D;
Grades g2 = Grades.F;
Console.WriteLine("First {0} a passing grade.", g1.Passing() ? "is" : "is not");
Console.WriteLine("Second {0} a passing grade.", g2.Passing() ? "is" : "is not");

Extensions.minPassing = Grades.C;
Console.WriteLine("\r\nRaising the bar!\r\n");
Console.WriteLine("First {0} a passing grade.", g1.Passing() ? "is" : "is not");
Console.WriteLine("Second {0} a passing grade.", g2.Passing() ? "is" : "is not");
}
/* Output:
First is a passing grade.
Second is not a passing grade.
Raising the bar!
Raising the bar!
First is not a passing grade.
Second is not a passing grade.
*/
First is not a passing grade.
Second is not a passing grade.
*/
}
}
//</snippet2>
} //namespace Extension2

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@
<Nullable>enable</Nullable>
<ImplicitUsings>enable</ImplicitUsings>
<AssemblyName>ExtensionMethods</AssemblyName>
<StartupObject>Extension_Methods_Simple.Program</StartupObject>
<StartupObject>Extension2.EnumExtension.Program</StartupObject>
</PropertyGroup>

</Project>

0 comments on commit 3ce2e97

Please sign in to comment.