Extension Methods in C#

Introduction

I would like to share how to create Extension methods in C# and why we need to have them in C#.

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

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 the calculator
  • The library contains Add, Subtract and Divide methods
  • By mistake the developer forget to add a Multiply method

3. Consuming Library (Creation of client)

We have added a client (console application to consume this library) as in the following:

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 code above 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 in this situation we have multiple options.

Problem
  • We can raise a request to the third-party DLL company 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. Addi 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
 

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.

Multiply method

Conclusion

In this article we learned how to create an Extension method and why we actually need it.

Up Next
    Ebook Download
    View all
    Learn
    View all