An extension method is a static method whose first parameter is marked with this, allowing instance-style calls on a type without modifying that type. The technique keeps interfaces small while adding convenient operations externally. section 2.3 section 4.3.1
Extension methods are especially useful when an operation would make an interface unsafe, overly large, or coupled to a particular implementation. They can also create fluent interfaces over existing abstractions such as sequences, distributions, and immutable quadtrees. section 2.3 section 12.6
Common uses include:
- Move Push outside IImStack<T>, preserving covariance while retaining calls such as s.Push(item). section 2.3
- Add structural operations such as Embiggen, Center, North, and HasAllEmptyEdges to a minimal IQuad interface. section 4.3.7 section 4.3.1
- Adapt distributions into infinite sample sequences, then reuse sequence operations such as Take, Sum, and formatting helpers. section 12.6
- Package reusable calculations, such as Euclid’s GCD algorithm for integers and integer sequences. section 12.5
A covariant immutable stack
A covariant IImStack<T> cannot declare Push(T), because T would occur in an input position. Moving Push into an extension method leaves the interface covariant: IImStack<Animal> s = tigerStack; s = s.Push(new Giraffe()); section 2.3
Listing 12.5 Treating distributions as sequences of samples
public static class Extensions
{
[...]
public static IEnumerable<T> Samples<T>(
this IDistribution<T> distribution)
{
while (true)
yield return distribution.Sample();
}
public static string Comma<T>(this IEnumerable<T> ts) =>
string.Join(",", ts);
}
Inspect a complete extension that turns a distribution into an infinite IEnumerable<T> of samples, enabling familiar sequence operations. section 12.6




