Extension methods add functionality to a type without changing its class definition. A static method in a static class becomes callable with instance syntax when its first parameter uses this. section 5.15 section 5.9
Listing 5.30 The contents of the MyExtensionMethods.cs file in the Models folder
namespace LanguageFeatures.Models {
public static class MyExtensionMethods {
public static decimal TotalPrices(this ShoppingCart cartParam) {
decimal total = 0;
if (cartParam.Products != null) {
foreach (Product? prod in cartParam.Products) {
total += prod?.Price ?? 0;
}
}
return total;
}
}
}
Defines TotalPrices for ShoppingCart, handling nullable products while preserving ordinary instance-call syntax. section 5.9
The extension method can use only members already accessible on the target type; it does not bypass private or otherwise restricted members. A controller can therefore calculate a cart total with cart.TotalPrices(), even though ShoppingCart was not modified. section 5.9
Targeting an interface broadens reuse. Defining TotalPrices for IEnumerable<Product?> allows the same method to process a ShoppingCart or a Product array, producing identical totals. section 5.9.1
Filter before totaling
FilterByPrice uses yield to return products meeting a minimum price, allowing productArray.FilterByPrice(20).TotalPrices() to exclude cheaper items before calculating the result. section 5.9.2




