C# 3.0 Features: Extension Methods

Posted Monday, October 3, 2005 1:32 PM by C-Dog's .NET Tip of the Day
These can be kind of cool.  Extension methods are methods that act like they belong to a particular type.  Ok if that wasn't confusing enough.  Basically it allows you to add a method to a particular type even though that type doesn't have that method.  For example, you can create a Write method on an ArrayList.  You can do this without having to create a new custom type by inheriting.
The way extension methods compile and work seems to be like magic.  You define an extension method just like a static method, but you add the keyword this in front of the type that is getting passed in.
In the example below, this is used before an IEnumerable type.
public static void Write(this IEnumerable source)
{
    foreach (var item in source)
    {
        Console.WriteLine(item);
    }
}
You can then use this method on any type that implements IEnumber, for example an ArrayList or whatever.
So then you can access it like this:
ArrayList myList = new ArrayList();
// assume it already has some values
myList.Write();
That would then execute the extension method as if it were part of the class originally.

Read the complete post at http://www.dotnettipoftheday.com/blog.aspx?id=51