Extension Methods
Extension methods are methods added to an existing type WITHOUT extending, recompiling or modifying the existing type. Extension methods are static
, however, they can be used as if they were instance methods. A frequently used example of extension methods is the Linq
library which adds a range of methods to collection objects using extensions.
You can define a new extension method for a particular type by creating a static
class and defining a static
method on that class, the first parameter of which specifies the type which the extension method extends preceded by the this
keyword.
namespace ExtensionMethods
{
public static class MyExtensions
{
public static void Print(this String str)
{
Console.WriteLine(str);
}
}
}
You can call an extension method by importing the namespace of the extension and then calling it as if it were instance method on the object. The compiler uses an intermediate language to convert the call generated by the extension method to a static method.
using ExtensionMethods;
var str = "Message";
str.Print() // => message
Extension Rules
Extension methods cannot access private variables on the type that they are extending.
Extension methods cannot override instance methods that already exist on the type they are extending, they always have a lower priority than the instance methods.
Extending Generics
You can extend generic interfaces by using generic specifiers before your extension methods. By creating an extension for types that implement the IEnumerable
interface this allows the extension method make use of foreach
inside its body.
public static bool EnumerableExtension<T>(this IEnumerable<T> enumerable, T comparison)
{
var result = false;
foreach(var t in enumerable)
{
result = (t == comparison);
}
return result;
}
You can generalise this extension pattern to delegates allowing you to pass in methods that can be run by the extension method. The example below extends the IEnumerable
to take a closure which expects as its input the same T
type that the enumerable holds.
public static bool Any<T>(this IEnumerable<T> enumerable, Func<T, bool> function)
{
var result = false;
foreach (var t in enumerable)
{
result = function(t);
}
return result;
}