Gunnar Peipman's ASP.NET blog

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.


using System;
using System.Security.Cryptography;
using System.Text;

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.

Comments

Christopher Steen said:

ASP.NET Detecting AJAX Requests in MonoRail [Via: Bill Pierce ] ASP.Net MVC Framework - Create your...

# November 18, 2007 1:42 AM

Christopher Steen said:

Link Listing - November 17, 2007

# November 18, 2007 1:43 AM

K Jacobson said:

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

# November 28, 2007 12:59 AM

Gunnar Peipman's ASP.NET blog said:

This blog entry is supposed to be the continuation for entry C# Extension Methods where I told what extension

# December 29, 2007 6:02 AM

???????????????????? ????????????: C#, ????????????, ????????????????????????????????, ????????, ????… « ???????? ???????????? ?????????????? said:

Pingback from  ???????????????????? ????????????: C#, ????????????, ????????????????????????????????, ????????, ????&#8230; &laquo; ???????? ???????????? ??????????????

# January 1, 2008 12:28 PM

Gunnar Peipman's ASP.NET blog said:

During one SharePoint migration project I had problem with document versions comments. I needed some

# April 5, 2008 3:25 AM

Community Blogs said:

During one SharePoint migration project I had problem with document versions comments. I needed some

# April 5, 2008 3:29 AM

Sheikhi Mahnaz said:

thanks for your example .

# April 27, 2008 8:20 AM

Gunnar Peipman's ASP.NET blog said:

I discovered once myself automatically writing redirects like this: Response.Redirect( &quot;otherpage

# July 9, 2008 6:13 PM

Gunnar Peipman's ASP.NET blog said:

During one of my current projects I wrote some useful extension methods for DateTime class. I had to

# July 16, 2008 3:20 PM
Leave a Comment

(required) 

(required) 

(optional)

(required)