Extension methods enable you to "add" methods to existing types without creating a new derived type, recompiling, or otherwise modifying the original type. Extension methods are a special kind of static method, but they are called as if they were instance methods on the extended type. For client code written in C# and Visual Basic, there is no apparent difference between calling an extension method and the methods that are actually defined in a type.
namespace ExtensionMethods { public static class MyExtensions { public static int WordCount(this String str) { return str.Split(new char[] { ' ', '.', '?' }, StringSplitOptions.RemoveEmptyEntries).Length; } } }
using ExtensionMethods;
string s = "Hello Extension Methods"; int i = s.WordCount();
This topic shows how to implement your own extension methods for any type in the .NET Framework Class Library, or any other .NET type that you want to extend. Client code can use your extension methods by adding a reference to the DLL that contains them, and adding a usingdirective that specifies the namespace in which the extension methods are defined.
Define a static class to contain the extension method.
The class must be visible to client code. For more information about accessibility rules, see Access Modifiers (C# Programming Guide).
Implement the extension method as a static method with at least the same visibility as the containing class.
The first parameter of the method specifies the type that the method operates on; it must be preceded with the this modifier.
In the calling code, add a using directive to specify the namespace that contains the extension method class.
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.