Tuesday, April 8, 2008

Extension Methods

You can write new methods to add to existing .NET classes without having to inherit the class. These can be common functions you always find yourself doing that you wish .NET could do out of the box. For example, doing string.Format on strings.
Before:
string name = "Mark"; 
string message = "Hello, my name is {0}."; 
return string.Format(message, name); 

After:
// ExtensionMethods.cs
public static class StringExtensionMethods
{
    public static string FormatThis(this string s, string arg)
    {
        return string.Format(s, arg);
    }
}

// Code elsewhere
string name = "Mark";
string message = "Hello, my name is {0}.";
return message.FormatThis(name);
Notice:
1. Your extension method and the class it is in has to be static.
2. The first argument is "this", "this" is the actual object you are extending.

More Info: Scott Guthrie: New "Orcas" Language Feature: Extension Methods