Extension methods
Extension methods are a convenient way of adding methods to classes that you do not own and cannot modify directly.Listing 4-11. The ShoppingCart Class in the ShoppingCart.cs File.
shows a ShoppingCart class, which I added to the Models folder in a file called ShoppingCart.cs file and which represents a collection of Product objects.
This is a simple class that acts as a wrapper around a List of Product objects.
Problem
Suppose I need to be able to determine the total value of the Product objects in the ShoppingCart class, but I cannot modify the class itself, perhaps because it comes from a third party and I do not have the source code.
Solution
I can use an extension method to add the functionality I need.
Listing 4-12 shows the MyExtensionMethods class that I added to the
Models folder in the MyExtensionMethods.cs file.
I can refer to the instance of the ShoppingCart that the extension method has been applied to by using the cartParam parameter.
My method enumerates the Products in the ShoppingCart and returns the sum of the Product.Price property.
Listing 4-13 shows how I apply an extension method in a new action method called UseExtension I added to the Home controller.
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. Here is the result from the UseExtension action method, which you can see by starting the application and
navigating to the /Home/UseExtension URL:
My method enumerates the Products in the ShoppingCart and returns the sum of the Product.Price property.
Listing 4-13 shows how I apply an extension method in a new action method called UseExtension I added to the Home controller.
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. Here is the result from the UseExtension action method, which you can see by starting the application and
navigating to the /Home/UseExtension URL:
Applying Extension Methods to an Interface
I can also create extension methods that apply to an interface, which allows me to call the extension method on all of the classes
that implement the interface. Listing 4-14 shows the ShoppingCart class updated to implement the
IEnumerable<Product> interface.