Extension Methods in C#

 Extension Method in C#

In this article, I will try to explain what an Extension Method is and in which scenario it is used.

Extension Methods are a feature in C# by which we can add a method for a class that we do not own without actually putting the method in it.

Developers can call an Extension Method using an object of the class for which the method is extended.

But when is it useful to use the Extension Method feature in our project?

Suppose we have purchased a class, let's say Sales class, in which a method is there for sending an email after a sales order is received. We want one more method to be there in the class for sending a SMS after a sales order has been received. But the problem is that we can't add this method to the Sales class since we do not have its source code with us, we have a DLL.

We also cannot inherit this class because it's a sealed class or we are not interested in creating a new class using inheritance at all.

If we want to add methods to the classes provided in the .Net Framework then we would use an Extension Method as shown in the following example.

We will create a console application known as InventoryManagement as shown in the following Figure 1.

Figure 1.

EM01

We have a Sales class provided by a third-party, but no source code; only the DLL is available to us. We will add a reference to this DLL as shown in Figure 2.

Figure 2.

EM02

We have only two methods, SaveOrder and SendEmailAfterSalesOrder in Sales class.

We also have sales-related properties, such as OrderId, InvoiceNo, Products, OrderDate and so on.

Now we will create a new static class and name it, let's say, ExtendingSales and add a static method SendSMSAfterSalesOrder that we think should have been in the Sales class.

We will add an argument of type Sales with this modifier in front of the argument as shown in the following Figure 3.

Figure 3.

EM03

Now we have added an Extension Method for the Sales class.

The code looks as shown in the following figure.

Now we can call the SendSMSAfterSalesOrder method using an object of the Sales class. This is shown in the following figure.

EMI04.jpg

NOTE:

The Extension Method concept also applies to interfaces.

An Extension Method will not be called if the class for which the method is extended has a method with the same name and signature.

We can use an Extension Method to add functionality to enums.

Up Next
    Ebook Download
    View all
    Learn
    View all