Extension Methods in C#

Extension Method :- As name suggests Extension means to "add something new to legacy" without affecting the original functionality.Extension Method is a special kind of method used for providing the extension of the existing functionalities of any Class.

Let me explain this in details using a Example - If you have a Class consider it as Employee class and inside this Employee Class there is a method calculating the bonus for all the Regular employees based on some standard formulas. Assume that after few months management decided to hire the employee on Part Time basis and they are also eligible for bonus on Sales but with different formula. In this situation you have two options

First Option :- You need to change the code in Employee class method and modifies it with adding the new formula for PartTime employee also but here is a design issue if any other department also using the previous code then they will get a error and you need to do some changes in other classes also that is required more efforts and it is very complex to debugging the system.

Second Option :- You can remains legacy classes as same as previous and you can extend the original class using the Extension Methods. Extension Method provides a way to add functionalities on class without affecting them so it will not impact on any others code. It provides the flexibility to adding new code and managing it seperately.

So come back to our example and using extension method we can write a logic for calculate bonus for PartTime employee and application will work fine throughout the projects.

How to write Extension Method in C# ?

Implementation Details :- Below is the key steps to write a Extension Method.

  • Create a base class and write a methods and data members into it as in our example Employee class and define the CalculateBonus() method into it for calculating the bonus for all the regular employees.
  • Create a Static Class for extention method in our example it is EmployeeExtension class.
  • Define a Static Method that is extention method for calculating the bonus for PartTime employees , in our example it is named as CalculateBonusForPartTimeEmployee().
  • Use this keyword with first parameter of extension method.
  • First Parameter should be a object of Legacy class to passed into it.
  • Create a object of legacy class into the calling class and called the newly written extension method using this object.
  • Run the application it will work as expected without affecting the original functionality of the class.

Here I have attached all the screen images for code and code snippet also , you can find all the code and do the practice in your system.

Image is not available
                
 public  class Employee 
    {
        public decimal CalculateBonus(int Salary,int totalSales)
        {
            decimal bonus = Salary + 2000; 
            if(totalSales > 500000 && totalSales < 1000000)
            {
               bonus=Convert.ToDecimal(Salary + (Salary * 10) / 100);
            }
            if (totalSales > 1000000 && totalSales < 30000000)
            {
                bonus = Convert.ToDecimal(Salary + (Salary * 12) / 100);
            }
            return bonus;
        }
    }
                 
                
Image is not available
                
 public static class EmployeeExtension
    {
        public static decimal CalculateBonusForPartTimeEmployee(this Employee employee, int Salary, int totalSales)
        {
            decimal bonus = Salary + 1000; ;
           if (totalSales > 500000 && totalSales < 1000000)
            {
                bonus = Convert.ToDecimal(Salary + (Salary * 1) / 100);
            }
            if (totalSales > 1000000 && totalSales < 30000000)
            {
                bonus = Convert.ToDecimal(Salary + (Salary * 1.5) / 100);
            }
            return bonus;
        }
    }
                 
                
Image is not available
                
 internal class Program
    {
        static void Main(string[] args)
        {

            Employee emp = new Employee();
            decimal RegularempBonus= emp.CalculateBonus(50000, 750000);
            decimal PartTimeempBonus = emp.CalculateBonusForPartTimeEmployee(50000, 750000);
            Console.WriteLine("Regular Employee Has Bonus on 750000 Sales :- " + RegularempBonus);
            Console.WriteLine("Part Time Employee Has Bonus on 750000 Sales :- " + PartTimeempBonus);
            Console.ReadKey();
        }
    }
                 
                
Image is not available

Image is not available

About the Author
Sudheer Singh Chouhan is a Software Engineer having Expertise in Development Design and Architecting the applications , Project Management , Designing Large Scale Databases in SQL Server since last 17 Years.
Skill Sets :- Microsoft .NET technologies like ASP.Net Core, Web API, LINQ, Web Forms, WinForms, SQL Server, EntityFramework, Design Patterns, Solid Principles, Microservices, AWS Cloud.