Extension method is a method injected (added) into an existing class (or struct or interface), without modifying the source code of that class (or struct or interface).
Existing Class
class ClassName
{
}
Static Class for Extension Method
static class ClassName
{
public static ReturnType MethodName(this ClassName ParameterName, …)
{
method body here
}
}
- You can add additional methods to pre-defined classes / structures such as String, Int32, Console etc.
- You must create a static class with a static method; that it will be added as a non-static method to the specified class.
- The first parameter of extension must be having “this” keyword; followed by the class name / structure name, to which you want to add the extension method. Eg: this ClassName parameter
- The parameter (with ‘this’ keyword) represents the current object, just like “this” keyword in the instance methods.
- Extension method can have any no. of additional parameters, where the “this” keyword parameter is must.
- Extension method does not support method overriding. That means, extension method’s signature can’t be same as any existing method.
- You can also add extension methods to sealed class.
- ‘Extension Methods’ concept can’t be used to create fields, properties, or events.
- The static class of extension method can’t be inner class.
- The namespace in which the static class of extension method is created, must be imported in order to call the extension method as non-static method