Extension Method in C#

Extension Method in C#

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
  }
}

  1. You can add additional methods to pre-defined classes / structures such as String, Int32, Console etc.
  2. You must create a static class with a static method; that it will be added as a non-static method to the specified class.
  3. 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
  4. The parameter (with ‘this’ keyword) represents the current object, just like “this” keyword in the instance methods.
  5. Extension method can have any no. of additional parameters, where the “this” keyword parameter is must.
  6. Extension method does not support method overriding. That means, extension method’s signature can’t be same as any existing method.
  7. You can also add extension methods to sealed class.
  8. ‘Extension Methods’ concept can’t be used to create fields, properties, or events.
  9. The static class of extension method can’t be inner class.
  10. 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

Comments

No comments yet. Why don’t you start the discussion?

Leave a Reply