In this post, we will discuss what are Extensions method in C#.Net.
If your source code is available then there are different ways to extend the class like through inheritance you can add functionality to the objects. But what will happen if you do not have the source code. In C#.Net Extensions method will help us in changing the class without having the source code.
Extension methods are static methods that can appear to be part of a class without actually being in the source code for the class.
Suppose we have a class name as Employee which class has some methods defined in it. But we want another method like AddBonous (decimal bonus amount). But we do not have the source code, so we can not directly change in the assembly.
To add the method we have to create a static class as well as we have to add the method AddBonous as a static method like below:
public static class EmployeeExtension
public static void AddBonous (this Employee employee, decimal bonus amount)
employee.Salary += bonus amount;
Here the first parameter is the type that is being extended preceded by this keyword.
This is what tells the compiler that this method is part of the Employee type. Here Employee is the type that is being extended. In the extension method, you have access to all the public methods and properties of the type being extended.
But while using the method the first parameter will not come means you can access the method like obj.AddBonous (5000);
Event through the method is a static method we have to use the standard instance method syntax to call the method. But If the extension method has the same name as a method in the class, the extension method will never be called.
Also, you can read:
You May Also like the Following SharePoint Tutorials: