Introduction to extension methods
What it is
Extension methods allow you to extend an existing type without needing access to the type's code. Before .NET 3.5, this wasn't possible without having access to the type's code or without using the System.Reflection.Emit namespace.
In short, extension methods are static methods that can be executed by instances of the extended object. Behind the scenes, the call to the extension method is nothing more then a call to a static method.
Behind the scenes, extension methods are marked with the System.Runtime.CompilerServices.ExtensionAttribute which is located in the Systme.Core.dll. So a reference to this DLL is necessary in order to create extension methods.
When to use
If you have a class that you want to extend but you don't have the source code, extension methods can be an answer. Also when extending a class with extension methods, you don't have the risk of breaking existing code which you can have when changing the type's definition.
Simple sample
In this sample, I'm adding a method IsWeekend to the DateTime type which will return a boolean to indicate whether a given date falls in the weekend or not.
using System;
class Program
{
static void Main(string[] args)
{
// Tuesday
DateTime d1 = new DateTime(2008, 1, 1);
// Saturday
DateTime d2 = new DateTime(2008, 1, 5);
Console.WriteLine("{0:d} is weekend: {1}",
d1, d1.IsWeekend());
Console.WriteLine("{0:d} is weekend: {1}",
d2, d2.IsWeekend());
}
}
public static class MyUtils
{
public static bool IsWeekend(this DateTime date)
{
return (date.DayOfWeek == DayOfWeek.Saturday
|| date.DayOfWeek == DayOfWeek.Sunday);
}
}
Extension methods must be created within a static class (each method within the class must be static as well). The first parameter of the method is marked with the this keyword and indicates the type to which the method should be applied (in this case DateTime). It is possible to add multiple parameters. Only the parameters after the first parameter, should be provided when using the method.
When you've implemented an extension method for a specific type, you will see that it is showed by intellisense with a specific icon.

It is possible to create a separate assembly with all your extension methods. Note that you need to add using statements for the namespaces where the extension methods are located.
2 comments:
Geert,
If I'm not wrong, extension methods aren't available in .NET 3.0 but in 3.5. It seems that you made a confusion between C# version (3.0) and framework.
Anyway, thank for sharing this.
Regards,
Stéphane.
ps: nice tips to get them on a previous version of the framework:
http://blogs.msdn.com/jaredpar/archive/2007/11/16/extension-methods-without-3-5-framework.aspx
You're correct, I've changed it.
Thanks for the feedback!
Post a Comment