Create And Use An Extension Method In C#


I would like to share how to create an extension method in C#, why do we need it, and how to use it in our C# application. 

First we will discuss the problem and then will rectify the problem using an extension method.

Understanding the problem

1. Add a Class library as per the following screen. We created a Calculator library.

Add Class library

2. Add the Calculator class as per the screen below.
Add calculator class

  1. public class Calculator  
  2. {  
  3.     public int Add(int x, int y)  
  4.     {  
  5.         return x + y;  
  6.     }   
  8.     public int Subtract(int x, int y)  
  9.     {  
  10.         return x - y;  
  11.     }  
  13.     public int Divide(int x, int y)  
  14.     {  
  15.         return x / y;  
  16.     }  
  17. }  
Understanding the code
  • We created a class library for calculator
  • The library contains Add, Subtract and Divide methods
  • By mistake the developer forget to add a Multiply method
Build and run the library.

3. Consuming Library (Creation of client)

Create a client application, a console application to consume this library. We call it CalculatorClient as shown below:

Consuming Library

4. Add a refrence of the Calculator library as created above.

Adding refrence

5. Add a reference to the class file as per the screen below:

Adding reference to class file
Here in the above code, we created an object of the Calculator class and we can see here Multiply method is not available because the developer forget to add it.

So, now we have multiple options.

We can raise a request to the third-party DLL company and ask them to add the required functionality. But it is a long process and it would also affect the cost and delivery of the project because we need to wait until we get a new DLL from the company

Solution: we can use an extension method to add a multiply method of this calculator class without modifying the DLL.

6. Add an Extension class. This should be a static class.

Adding Extension class

7. We added a Multiply method as per the screen below.
added Multiply method

Sample code
  1. namespace CalculatorClient  
  2. {  
  3.     public static class ExtensionClass  
  4.     {  
  5.         public static int Multiply(this CalculatorThirdPartyLib.Calculator obj, int x, int y)  
  6.         {  
  7.             return x * y;  
  8.         }  
  9.     }  
  10. }  

8. Compile the code.

9. Now as per the screen below we can see the Multiply method is now available to the object of the Calculator class.
Multiply method


In this article, we learned how to create an extension method and why we actually need extension methods. 

Here is another detailed tutorial, Extension Methods In C#.

Similar Articles