1.3. Extension Methods

As the name implies, extension methods extend existing .NET types with new methods. For example, by using extension methods with a string, it's possible to add a new method that converts every space in a string to an underscore. Listing 1-3 provides an example of an extension method.

Example 1-3. An Extension Method
public static string SpaceToUnderscore(this string source)
{
    char[] cArray = source.ToCharArray();
    string result = null;

    foreach (char c in cArray)
    {
        if (Char.IsWhiteSpace(c))
            result += "_";
        else
           result += c;
    }

    return result;
}

Here you define an extension method, SpaceToUnderscore(). To specify an extension method you insert the keyword this before the first method parameter, which indicates to the compiler ...

Get LINQ for Visual C# 2008 now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.