C# Extension Methods

Extension methods allow you to add new methods to existing classes without sub-classing them. Say we wanted a clean way to enforce a maximum string length of no more than 5 characters. We could write a Crop method and call it like this:

public void Main()
{
  string myString = "Hello World";
  Console.WriteLine(Crop(myString, 5));
}

private string Crop(string value, int maxLength)
{
  if (value.Length > maxLength)
    return value.Substring(0, maxLength);
  else
    return value;
}

This is perfectly ok. However, sometimes you may find this a little clunky to read. We could re-write the above example as this:

public void Main()
{
  string myString = "Hello World";
  Console.WriteLine(myString.Crop(5));
}

/* This should be placed in a different file */
public static class ExtensionMethods
{
  public static string Crop(this string value, int maxLength)
  {
    if (value.Length > maxLength)
      return value.Substring(0, maxLength);
    else
      return value;
  }
}

Note the carefully placed ‘this’ keyword before our first parameter. In our context ‘this’ tells the compiler to treat the method as an extension method, and to apply it to all objects that match the parameter’s type. Extension methods must be placed in a non-generic static class.

IntelliSense now treats the Crop method as a member of the String type, with only one parameter – the first parameter is always hidden.

For more information, MSDN is your friend:
http://msdn.microsoft.com/en-us/library/bb383977.aspx

Advertisements
This entry was posted in Tips and Tricks and tagged , . Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s