# 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.

namespace MyExamples{    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)        {            MD5CryptoServiceProvider provider;            provider = new MD5CryptoServiceProvider();            byte[] bytes = Encoding.UTF8.GetBytes(s);            StringBuilder builder = new StringBuilder();             bytes = provider.ComputeHash(bytes);             foreach (byte b in bytes)                builder.Append(b.ToString("x2").ToLower());             return builder.ToString();        }    }}

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.WriteLine(s.Nl2Br());    Console.WriteLine(s.MD5());    Console.Write("Press any key...");    Console.ReadLine();}

If everything is okay we will get the following output:

    First<br />Second<br />Third     22738d44da2809b621cc6e6609152c72



    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.

### 2 thoughts on “C# extension methods”

• K Jacobson says:

Really looking forward to taking advantage of these in the new C# release, but I agree need to be careful not to overdue it.

• Sheikhi Mahnaz says:

thanks for your example .

• […] Extensions methods are pretty powerful thing because we can extend existing types without inheriting from them. I don’t know developers who want to extend string or int or other basic types offered by .Net Framework. […]