Extension Method in C#

Extension methods allow you to add methods to existing types. And the interesting thing is that you can do it without adding this method or updating the original type.

To define and call extension methods consider the following points:

  1. Define a static class that contains the extension method.
  2. Define the extension method as static method.
  3. Add the first parameter with 'this keyword' upon which this extension method has to be operated on.
  4. If the calling class and the class which contains the extension method then add 'using' directive to specify the namespace which contains the extension method's class.
  5. Now you can call the extension method as it is the instance method of this type.

Example:

  1. string s="My name is Usman";  
  2. s.Display(10); //Display this name ten times  
Now the point is "Is there any Display method in string class ?The answer is no." But with extension method you can do it without updating the string class and even you can call this method with the instance of string class.

  1. This is Class which contains the extension methods. Both class and extension method are with static and as we have to call this method on string so we would use 'this keyword for first parameter .

    Class

  2. This is the calling class which calls the extension method. In this class you declare a string object 'name'. There is no Display method which can be called with the string object.But with the extension method you can do that.

    extension method

Output:

Output