Powered by Blogger.

Sunday, February 23, 2014

Extensions method in C#.Net

In this post we will discuss about what are Extensions method in C#.Net.

Also check out:

- Singleton class in C#.Net

- How to set enum values with spaces in c#.net?

- Export gridview data to excel sheet in Asp.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 (decima bonousAmount). 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 bonousAmount)
employee.Salary += bonousAmount;

Here the first parameter is the type that is being extended preceded by the 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.