Monday, 4 May 2009

Extension Methods

By using the this keyword you can add to (extend) any class, even sealed classes. So

public static string ToTitleCase(this string value)
{
...
}

allows you to do the following;

string state = "south west australia";
Console.WriteLine(state.ToTitleCase());

You can extend even interfaces so if you create;

public static IEnumerable WhereEven(this IEnumerable values)
{
...
}

You will find the WhereEven method is available on List, Collection, int[ ] and anything else that implements IEnumerable.