18 11 2007
C# extension methods
One of new cool features that will be available in C# 3.0 are extension methods. Extension methods will allow us to extend existing classes with new functionality. In this example I will show you how to extend System.string with two methods that are very popular in PHP: nl2br() and md5().
Extension methods must be defined as static methods of some static class. Now let’s write the static class called StringExtensions.
static class StringExtensions
public static string Nl2Br(this string s)
return s.Replace("\r\n", "<br />").Replace("\n", "<br />");
public static string MD5(this string s)
provider = new MD5CryptoServiceProvider();
byte bytes = Encoding.UTF8.GetBytes(s);
StringBuilder builder = new StringBuilder();
bytes = provider.ComputeHash(bytes);
foreach (byte b in bytes)
Notice the argument list of these function, especially keyword this. Keyword this followed by type tells to compilator that this method is applied to specified type.
Now let’s try out our new methods.
static void Main(string args)
string s = "First\r\nSecond\nThird";
Console.Write("Press any key...");
If everything is okay we will get the following output:
First<br />Second<br />Third
Press any key...
Pretty convenient, isn’t it?
Although extension methods are very powerful feature in new C# it has to be mentioned that over-using them may lead you to very bad problems. Your code might be hard to maintain and understand for you and the other programmers. But in the case of sensible use of extension methods you will find them to be very convenient and powerful features that help you a lot.