Extension Methods in C#


By using extension methods we can add the new functionality to existing class even though you don’t have permissions to change that class code, but we should have access for that class. There some basic rules we have to follow to implement the extension methods. The extension method should be static and it has to be in static class. It should use the “this” keyword as the first parameter with the class name to which it extends the functionality. We can access this extension method by using the instance of the class on the client side.

Open Microsoft Visual Studio 2013 => Create new project and add below class.

using System;

using System.Collections.Generic;

using System.Linq;

using System.Web;

 

namespace EmployeeData

{

    public class Company

    {

        public List<Employee> Employees { get; set; }

    }

 

    public class Employee

    {

        public int EmpId { get; set; }

        public string EmpName { get; set; }

        public decimal EmpSal { get; set; }

    }   

}

 

As shown above we have company class which contains Employees automatic public property of Employee list type. Let’s create extension method for the Company class to calculate sum of all Employees salary as shown below.

using System;

using System.Collections.Generic;

using System.Linq;

using System.Web;

 

namespace EmployeeData

{

    public static class ExtensionClass

    {

        public static decimal TotalEmpSal(this EmployeeData.Company company)

        {

            decimal totalSal = 0;

            foreach (Employee emp in company.Employees)

            {

                totalSal = totalSal + emp.EmpSal;

            }

 

            return totalSal;

        }

    }

}


As shown above we have created ExtensionClass class and implemented the extension method TotalEmpSal() for the Company class. We are passing the Company type to TotalEmpSal() method by prefixing “this” keyword. Prefixing this keyword tells .Net TotalEmpSal() is the extension method for the Company class. We can access this extension method by using Company class instance as shown below.

using EmployeeData;

using System;

using System.Collections.Generic;

using System.Linq;

using System.Web;

 

namespace ExtensionMethodExample

{

    public class Example

    {

        public decimal AllEmployeeSal()

        {

            Company obj = new Company();

            decimal dEmpSal = obj.TotalEmpSal();

 

            return dEmpSal;

        }

    }  

}


Extension method do not allow you to break the access rules that classes define for their methods, properties, fields.