I would like to share how to create Extension method in c# and why we need to
have this method in C#.
First we will discuss the problem and then will rectify the problem using Extension
Understanding the problem
1. Add Class library as per below screen. We created Calculator library.
2. Add calculator class as per screen below.
public class Calculator
public int Add(int x, int y)
return x + y;
public int Subtract(int x, int y)
return x - y;
public int Divide(int x, int y)
return x / y;
Understanding the code
- We created class library for calculator
- Library contains Add, Subtract, Divide methods
- By mistake developer forget to add Multiply method
- Consuming Library (Creation of client)
We have added a client (console application to consume this library)
- Adding refrence of Calculator library as created above.
- Adding reference to class file as per screen below
Here in code above we have created an object of Calculator class and we can see
here Multiply method is not available because developer forget to add.
So in this situation we have multiple options.
a. We can raise a request to Third party dll company to add required
But it is long process and it would also affect cost and delivery of project because
we have to wait until we get new dll from company
b. We can use Extension method to add multiply method of this calculator class
without modifying dll.
- Adding Extension class
This should be static class
- We added Multiply method as per screen below.
public static class ExtensionClass
public static int Multiply(this CalculatorThirdPartyLib.Calculator obj, int x, int y)
return x * y;
- Compile code
- Now as per screen below we can see Multiply method is now available to
object of calculator class
In this article we learned how to create Extension method and why actually we