liveBook · Manning

Extension

As explained in Pro ASP.NET Core 7, Tenth Edition

An extension method is a statically defined method that can be invoked with instance-method syntax on a type without modifying that type's definition.

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

How Pro ASP.NET Core 7, Tenth Edition covers it

How deep it goes
Defines static classes, this parameters, interface targets, nullable handling, and yield-based filtering, but does not discuss compiler transformation internals.
Examples
Uses ShoppingCart, Product arrays, TotalPrices, FilterByPrice, controller actions, browser URLs, and displayed currency totals.
What it assumes
Assumes familiarity with classes, objects, static methods, interfaces, nullable values, collections, and foreach iteration.
What you can do after
Build new operations for inaccessible classes, reuse them across interface implementations, and compose filtering with aggregation.
How it connects
Connects extension methods to static classes, interfaces, IEnumerable<T>, nullable reference types, foreach, and yield.

Also explained in

Compare how 5 books explain extension →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Pro ASP.NET Core 7, Tenth Edition. The section links point to the parts of the book it draws on.