C# Extension Methods

C# Extension methods are used to extend the functionality of an existing type without doing any modifications to the existing code, or by creating a new derived type. C# Extension methods are created as a static method with a special parameter preceded by this keyword.

The Extension methods act like instance methods but basically, they are a special kind of static method.

Following is the syntax to create an Extension method.

[access modifier] static [return type] MethodName(this TypeName parameterName)
{ 
	//method body 
}

In the following example, there is a class Customer. Suppose this class is residing in a DLL file and you don't have the access to original code. But still, you want to extend the functionality of this class without creating a new derived type.

Example

Try It
//Customer class defined in a DLL file
public class Customer
{
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public int Age { get; set; }
 
    public void PrintCustomerDetails()
    {
        Console.WriteLine("Customer Firstname is : {0} and last name is : {1}", FirstName, LastName);
    }
}
//Customer class Extension
public static class CustomerExtensions
{
    public static void PrintCustomerFull(this Customer customer)
    {
        Console.WriteLine("Customer Firstname is : {0} and last name is : {1} and customer age is : {2}", customer.FirstName, customer.LastName, customer.Age);
    }
}

public static void Main()
{
    Customer customer = new Customer();
 
    customer.FirstName = "Mark";
    customer.LastName = "Roger";
    customer.Age = 23;
 
    customer.PrintCustomerDetails(); //Instance method of Customer class
 
    customer.PrintCustomerFull(); //Extension Method of Customer class 
 
    Console.ReadKey();
}

The common example of C# Extension methods are Linq query operators.