Introduction
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.
2. Add the Calculator class as per the screen below.
Code
- 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 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:
4. Add a refrence of the Calculator library as created above.
5. Add a reference to the class file as per the screen below:
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.
Problem
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.
7. We added a Multiply method as per the screen below.
Sample code
- namespace CalculatorClient
- {
- public static class ExtensionClass
- {
- public static int Multiply(this CalculatorThirdPartyLib.Calculator obj, int x, int y)
- {
- return x * y;
- }
- }
- }
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.
Conclusion
In this article, we learned how to create an extension method and why we actually need extension methods.