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.
- First, create a static class, as extension method is always defined in a static class.
- The method should be static, it’s obvious, a static class must have static members.
- 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.
- class static class ExtentionMethods {
- public static int GetCount < T > (this IEnumerable < T > sequence) {
- int count = 0;
- foreach(var item in sequence) {
- count += 1;
- }
- return count;
- }
- }
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.
- class Student {
- public int Id {
- get;
- set;
- }
- public string Name {
- get;
- set;
- }
- }
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.
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,
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.