Overview Of Extension Method In C#

An extension method is the special type of static method which allows us to define a static method that appears to be a member of another type.

We can extend the value type and reference type like classes, interfaces. We can  even extend sealed type using extension method; however, sealed type does not allow inheritance. 

An extension method gives the flexibility to access static method with instance syntax.

Following are the steps in order to create an extension method.

  1. First, create a static class, as extension method is always defined in a static class.
  2. The method should be static, it’s obvious, a static class must have static members.
  3. The first parameter of an extension method always is a “this” modifier. It tells the compiler that you are dealing with an extension method.

Following is an extension method which takes IEnumerable<T>, T means any type which implements IEnumerable.

  1. class static class ExtentionMethods {  
  2.     public static int GetCount < T > (this IEnumerable < T > sequence) {  
  3.         int count = 0;  
  4.         foreach(var item in sequence) {  
  5.             count += 1;  
  6.         }  
  7.         return count;  
  8.     }  
  9. }  
Following is the description of the above code.
  • We create a static class ExtentionMethods.
  • The first parameter is this modifier in the above method.
  • Then we create a static method which gets the count of any type which implements IEnumerable.
  • Then we write business logic to count from the sequence.

How do we get to benefit from extension method?

Let’s suppose we have a student class.

  1. class Student {  
  2.     public int Id {  
  3.         get;  
  4.         set;  
  5.     }  
  6.     public string Name {  
  7.         get;  
  8.         set;  
  9.     }  
  10. }  
We can store student information in any collection - array or list. In this example, we store the student information in an array but you can store in the list also.
 
C#

Let’s see in the above code when we access extension method instance variable “students” using dot operator, IntelliSense gives a suggestion, and we can see the extension method which we created in suggestion.

We can identify an extension method. It has a signature. If a method has a down arrow, it means this is an extension method. As we can see in the above code, GetCount() extension method has a down arrow in front of it.

Below is the console output,

Output

Extension methods is heavily used in Lambda expressions, following are some,

  • First()
  • FirstOrDefault()
  • Single()
  • SingleOrDefault()
  • Where()
  • Take()

There are many other extension methods available for the lambda expression. We will take a deep dive in the next article.