Along with lambda expressions and iterators, C# 3.0 brought us extension methods. These static methods (contained in a static
class whose first argument is modified with the this
modifier) were created for LINQ so IEnumerable
types could be queried without needing to add copious amounts of methods to the IEnumerable
interface.
An extension method has the basic form of:
public static class EnumerableExtensions { public static IEnumerable<int> IntegerSquares( this IEnumerable<int> source) { return source.Select(value => value * value); } }
As stated earlier, extension methods must be within a static
class, be a static
method, and the first parameter must be modified with the this
modifier.
Extension methods extend the available instance methods of a type. In our previous example, we've effectively added an instance member to IEnumerable<int>
named IntegerSquares
so we get a sequence of integer values that have been squared.
For example, if...