
Introduction
Extension methods are new to C# 3.0 and enable you to extend existing types with new Methods. It's used for the new Query operators that are introduced with LINQ. After having done some articles[1][2] on LINQ I decided that it's a good idea to find out a little more about extension methods and how they work.
Creating extension methods
Extension methods are static classes containing a public static method where the first parameter is prefixed with the this keyword. It's important to know that you can only access public members of the class. The method is however not limited to void and can return any type. You can even use generics in the method.
namespace MyNamespace {
public static class PrintExtension {
public static void Print(this object objectToPrint) {
Console.WriteLine(objectToPrint.ToString());
}
}
}
Using extension methods
To use the extension method you need to import the namespace which contains the class with extension method. After that you can call the method in a similar fasion as shown below.
using MyNamespace;
public static class Program {
public static void Main(String[] params) {
int number = 123456789;
number.Print();
}
}
Extension method invocation
There's a special method of invocation for Extension methods, because extension methods aren't contained within the class definition of the instance on which the method call is actually made. The method call is rewritten to a static method call, where the identifier is resolved using a special lookup.
The compiler starts looking up the method in the type of the instance, if the method isn't find there it is looked up within types containing the extension methods accessable from the namespaces included in the class file with using statements. If no suitable type is found, the compiler gives an error.
Because of this mechanic, it's possible to have an instance method and an extension method with the same signature. In this case the compiler will generate IL code that rewrites the statement using the instance type. This also means that you might run into problems if an object has a method with the same signature as the extension method.
Sample
A good sample to show how powerful Extension methods are is hard to find, it's probably because I haven't seen much code yet that could use extension methods to solve a specific problem I had. The sample below shows how you can use an extension method to write generic code to convert an object to a different type using a TypeConverter.
namespace SimpleTypeConverter
{
public static class ConverterExtension
{
public static T ConvertTo<T>(this object objectToConvert)
{
TypeConverter converter = TypeDescriptor.GetConverter(objectToConvert);
if (converter != null && converter.CanConvertTo(typeof(T)))
return (T)converter.ConvertTo(objectToConvert, typeof(T));
else
throw new InvalidCastException(string.Format(
"Cannot convert {0} to {1}", typeof(T).Name,
objectToConvert.GetType().Name));
}
}
}
This extension method enables you to write a call like:
int number = 123456789;
String text = number.ConvertTo<String>();
Although for most conversions this extension method isn't useful, but it enables you to convert types that are only remotly convertable. Mostly where custom typeconverters are implemented which are normally only available through classes like Convert.
Conclusion
Extension methods are great, especially in the way Microsoft has used them to implement the Standard Query Operators. The best use for Extension methods in my opinion is for those cases where you need a method across several types and don't want to inherit from one base object or want to copy code from one spot to another spot.
[1] http://www.mein-design.nl/willem/posts/introduction-to-linq-part-1/
[2] http://www.mein-design.nl/willem/posts/introduction-to-linq-part-2/
[3] http://download.microsoft.com/download/5/8/6/5868081c-68aa-40de-9a45-a3803d8134b8/CSharp_3.0_Specification.doc