Extension methods are static method with a special syntax for the first parameter. The compiler allows you to use them syntactialy like instance methods.
public class ExampleClass
{
public String Value { get; set; }
}
Now you could introduce a method PrintValue()
by modifying the class.
public class ExampleClass
{
public String Value { get; set; }
public void PrintValueInstance()
{
Console.WriteLine(this.Value);
}
}
You could also create a static method in some class - ExampleClass
or any other.
public class AnyClass
{
public static void PrintValueStatic(ExampleClass exampleClass)
{
Console.WriteLine(exampleClass.Value);
}
}
And you can create an extension method - it's much like the static method, but marks the first parameter with this
.
public class ExtensionClass
{
public static void PrintValueExtension(this ExampleClass exampleClass)
{
Console.WriteLine(exampleClass.Value);
}
}
The ussage is then as follows.
ExampleClass example = new ExampleClass();
example.PrintValueInstance(); // Instance method
AnyClass.PrintValueStatic(example); // Static method
ExtensionClass.PrintValueExtension(example); // Extension method (long usage)
example.PrintValueExtension(); // Extension method
So the compiler allows you to use a static method with instance method syntax on objects that match the type of the first parameter. This allows you to add methods to a class without the need to modify the class. Of course, there is a limitation - you can only access public members from within a extension method.
You can also define extension methods for interfaces and they are then availiable to all classes implementing the interface.
public interface ISomeInterface
{
Int32 Foo(Int32 value);
Int32 Bar(String text);
}
public static class SomeInterfaceExtension
{
public static Int32 FooFooBar(this ISomeInterface @this, String text)
{
return @this.Foo(@this.Foo(@this.Bar(text));
}
}
Now the method FooFooBar()
is availiable on all classes implementing ISomeInterface
.
public class NiceClass : ISomeInterface
{
public Int32 Foo(Int32 value)
{
return value * value;
}
public Int32 Bar(String text)
{
return text.Length;
}
}
Now you can use the extension method on NiceClass
instance.
NiceClass niceClass = new NiceClass();
Console.WriteLine(niceClass.FooFooBar("ExtensionMethodExample"));