Sunday, May 4, 2008

How to extend classes using extension methods

In .NET 3.5 there is a new functionality called extension methods. Extension methods let you extend any classes in the .NET framework, 3rd party frameworks or your own frameworks with your own methods. Let's look at an example where we extend the System.String class with two new methods, to get the first five and last five characters of a string:

public static class StringExtension
{
 /// 
 /// Returns the first five characters of a string.
 /// 
 public static String GetFirstFiveCharacters(this String myString)
 {
  return myString.Substring(0, 5);
 }
 /// 
 /// Returns the last five characters of a string.
 /// 
 public static String GetLastFiveCharacters(this String myString)
 {
  return myString.Substring(myString.Length - 5, 5);
 }
}

In the example above, we use a class with the name StringExtension. However, you can name this class whatever you like: StringExtension, StringMethods, StringHelper, Helper etc. The only important thing is that your methods follow the pattern for extension methods:


public static  MethodName(this  variableName)

Now, let's produce some code using our extension methods:


String helloWorld = "Hello World";
String hello = helloWorld.GetFirstFiveCharacters(); // contains Hello
String world = helloWorld.GetLastFiveCharacters(); // contains World

Of course, extension methods are shown in the intellisense in Visual Studio.