Extensions method in C#.Net

InfoPath alternatives for form designing SharePoint

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:


– Free SharePoint Migration Tool from Microsoft step by step migration from SharePoint 2016 on premise to SharePoint Online

– SharePoint Approved and Rejected buttons not appearing in task form in Visual Studio 2015 workflow


You May Also like the Following SharePoint Online Tutorials:

About Bijay Kumar

I am Bijay from Odisha, India. Currently working in my own venture TSInfo Technologies in Bangalore, India. I am Microsoft Office Servers and Services (SharePoint) MVP (5 times). I works in SharePoint 2016/2013/2010, SharePoint Online Office 365 etc. Check out My MVP Profile.. I also run popular SharePoint web site SharePointSky.com

View all posts by Bijay Kumar →

Leave a Reply