C # Extension Method-from msdn,
The extension method enables you to "add" methods to existing types without creating a new derived type, re-compiling, or modifying the original type in other ways. An extension method is a special static method, but it can be called like an instance method of an extension type. For client code written in C # and Visual Basic, there is no significant difference between calling an extension method and calling a method actually defined in the type.
Compile code using the extension method:
namespace ExtensionMethods{ public static class MyExtensions { public static int WordCount(this String str) { return str.Split(new char[] { ' ', '.', '?' }, StringSplitOptions.RemoveEmptyEntries).Length; } } }
1. The static method is required.
2. The first parameter is the type to which the extension method is added (this type name row parameter name)
Introduce the namespace when calling:
using ExtensionMethods;
There is no obvious difference between calling an extension method and calling a method actually defined in the type:
string s = "Hello Extension Methods";int i = s.WordCount();
Note: In the code, you can use the instance method syntax to call the extension method. However, the intermediate language (IL) generated by the compiler converts the code into a call to a static method. Therefore, it does not really violate the encapsulation principle. In fact, extension methods cannot access private variables in their extended types.
You can use the extension method to extend the class or interface, but you cannot override the extension method. Extension methods with the same name and signature as interfaces or class methods will never be called. During compilation, the priority of the extension method is always lower than the instance method defined in the type itself. In other words, if a type has a method named Process (int I) and you have an extension method with the same signature, the compiler always binds it to this instance method. When the compiler encounters a method call, it first looks for a matching method in the instance method of this type. If no matching method is found, the compiler searches for any extension method defined for this type and binds it to the first extension method it finds.
Generally, we recommend that you implement the extension method only when you have to, and implement it with caution.