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 the type you want to extend. Note that the method and its class must be static. You can use SpaceToUnderscore() just like any other string method.

Figure 1-2 shows the result of executing this method.

Figure 1-2. Calling an extension method

The Where<T> and Select<T> methods, that the where and select clauses are transformed into are extension methods defined for the IEnumerable<T> interface. They are in the System.Linq namespace.

Simply by adding the new System.Linq namespace, you can use LINQ with any type that implements IEnumerable<T>. You don't have to install a new version of .NET or replace any existing assemblies. You do have to consider a couple of things when implementing and using extension methods, however:

  • If you have an extension method and an instance method with the same signature, priority is given to the instance method.

  • Properties, events, and operators are not extendable.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.145.45.5