What is mean by extension methods?

Extension methods are used for adding new functionality to an existing class without a change in the existing class or adding derived type. For this, we need to create the static class with a static method for new functionality where the “this” modifier to the first parameter of the method and the type of the first parameter is a type of that class which we want to extend.

class Employee
{
            public string GetEmployeeName()
            {
                return "Kiran";
            }

 }

 

Now we have to add a new method for getting the gender of the employee without adding derived class or change existing class,

see below code how we can achieve this:

 

                class Employee
             {
                         public string GetEmployeeName()
                         {
                              return "Kiran";
                         }
             }

static class EmployeeExtension
{
            public static string GetEmployeeGender(this Employee employee)
            {
                return "Male";
            }
}

             class Program
             {
                         static void Main(string[] args)
                         {
                              Employee e = new Employee();
    Console.Write(e.GetEmployeeName());
    Console.Write(e.GetEmployeeGender());
                         }

}

See above code, we added a new static class and declared one static method with one parameter where “this” modifier is used and type is the same as where we need to extend the functionality. And see we are now able to access the GetEmployeeGender() method using the instance of Employee type.

Post a Comment

0 Comments