C# Extension Methods
Thursday, August 7th, 2008I was explaining to a friend how to use extension methods and wrote up this quick sample.
namespace Foo.Extensions
{
public static class StringExtensions
{
public static string Truncate(this string value, int maxLength)
{
if (value.Length > maxLength)
return value.Substring(0, maxLength - 3) + "...";
return value;
}
}
}
To use the extension method:
using Foo.Extensions; // IMPORTANT!
namespace Foo
{
public static class Program
{
public static void Main(string[] args)
{
string longText = "this is some really long text!!!";
Console.WriteLine(longText.Truncate(20));
}
}
}
The magic happens when you add the this keyword to the first parameter of the static method. This tells the compiler to add the method to the specified type (string is this example). The method behaves as an instance method, though your extension method can only access public members of the type.
You can also call the extension method the old way: StringExtensions.Truncate(longText, 20);
It’s important to note that you MUST add a using statement to import the namespace where you defined the extension method (Foo.Extensions in this example), otherwise the compiler (and intellisense) won’t add the methods to the specified types.
Extension methods are one of the most useful additions to C# 3.0. They are simple to use and in many cases you can convert an existing method to be an extension method without breaking existing code.