CSharp - Method Extension Methods

Introduction

You can use extension methods to extend an existing type new methods without altering the definition of the original type.

An extension method is a static method of a static class, where the this modifier is applied to the first parameter.

The type of the first parameter is the type to be extended.

For example the following IsFirstLetterUpperCase extension method can be called as though it were an instance method on a string

public static class StrUtil
{
       public static bool IsFirstLetterUpperCase (this string s)
       {
         if (string.IsNullOrEmpty(s)) 
            return false;
         return char.IsUpper (s[0]);
       }
}
Console.WriteLine ("book2s.com".IsFirstLetterUpperCase());

An extension method call when compiled is translated back into an ordinary static method call:

Console.WriteLine (StrUtil.IsFirstLetterUpperCase ("Perth"));

The translation works as follows. Suppose we have the following static extension method.

StaticClass.Method (arg0, arg1, arg2, ...); // Static method call

It will be translated to

arg0.Method (arg1, arg2, ...);              // Extension method call

Interfaces can be extended, too:

public static T First<T> (this IEnumerable<T> sequence)
{
       foreach (T element in sequence)
         return element;

       throw new InvalidOperationException ("No elements!");
}


Console.WriteLine ("book2s.com".First());   // b

Extension Method Chaining

Extension methods provide a tidy way to chain functions.

Consider the following two functions:

public static class StrUtil
{
       public static string Pluralize (this string s) {...}
       public static string Capitalize (this string s) {...}
}

You can use the extension method as follows.

string x = "test".Pluralize().Capitalize();