Visual Studio 2008 and Framework 3.5 include an exciting new feature - extension methods. Extension methods enables writing custom methods and "attaching" them to existing classes inside the Framework. In other words, you can extend Framework classes with your own methods.
Let's demonstrate this through a simple example. We want to extend string class with ToShortString() method. This method will cut the string to a maximum 50 characters and add three dots at the end of the string. This might be useful to create an "abstract" of news or blogs.
Let's look at the code below. There are few simple steps you have to follow in order to create a extension method:
- Extension methods have to be static, and to be a part of a static class.
- You can give any name to your class, and you can place it in your own namespace.
- You have to add "this" keyword in the input parameter that points to a type you are extending
public static class ExtensionMethods
/// Cuts the string to a maximum of 50 charactes
/// <param name="text"></param>
public static string ToShortString(this string text)
string shortText = text;
if (text.Length > 49)
shortText = text.Substring(0, 50) + "...";
Using new method is quite simple. Assign some text to a string variable and when you type "dot", intellisense will list extension method in a method list. Note that your new method will have a slightly different icon in the list, and it will have "(extension)" prefix in the tooltip description (see image below).
You can use extension methods to extend other types as well. For example, you can extend DateTime class to return the number of hours remaining to the end of the week. Or you can extend decimal class to return the number on the right side of decimal point as a integer or string.
Use your imagination! :)