Extension methods in C#

Avinash Karat
2 min readSep 4, 2021

To simply put, Extension methods are a convenient way of adding methods to classes that you cannot modify directly, typically because they are provided by a third-party package.

Lets look at an example of a ShoppingCart class which contains a collection of Product objects.

Suppose I need to be able to determine the total value of the Product objects in the ShoppingCart class. But here I cannot modify the class because it comes from a third party, and I do not have the source code. In this type of scenario I can use an extension method to add the functionality I need.

Add a class file named OurExtensionMethods.cs in the same hierarchy folder of the shopping cart class, and use it to define the class.

Usually extension methods are defined in static classes within the same namespace as the class the extension methods applies to. Extension methods are also static. Here in our class, it defines a single extension method named TotalPrices. The this keyword in front of the first parameter marks TotalPrices as an extension method. The first parameter tells .NET which class the extension method can be applied to — ShoppingCart in this case. I can refer to the instance of the ShoppingCart that the extension method has been applied to by using the cartParam parameter. This extension method enumerates the Product objects in the ShoppingCart and returns the sum of the Product.Price property values.

The following code shows how we can use the extension method in action:

Here I call the TotalPrices method on a ShoppingCart object as though it were part of the ShoppingCart class, even though it is an extension method defined by a different class altogether. .NET will find extension classes if they are in the scope of the current class, meaning that they are part of the same namespace or in a namespace that is the subject of a using statement

Conclusion:

Just give it a try and let me know how it goes:

Thanks for reading!

--

--

Avinash Karat

Working professionally as a full stack .Net developer . Also have a keen interest in personal productivity, meditation&personal finance. Here to share things.