Monday, April 28, 2008

.NET 3.0 - Use Extension Methods to Simplify Your Code!

How would you like to have syntax like this that is fully IntelliSense capable?

List<string> list = new List<string>();
list.Add("john@email.com");
list.Add("joe@email.com");
list.Add("james@email.com");
Console.WriteLine(list.ToDelimitedString(","));
////or this...
string emailAddress = "test@test.com";
Console.WriteLine(emailAddress.IsEmailValid().ToString());

Now with the new .NET 3.0 Extension methods it is extremely trivial:

  1. Create a non-generic static class. This will contain the extension methods.
  2. Create a static method where the first parameter uses the type you would like to extend. It must also be prefixed by the "this" keyword. Note: this can be any type, including those that you create yourself.
  3. Simply call the extension method from an instantiated type. You will see that the extension method is added to the list of IntelliSense members.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace TestConsoleApp
{
    class Program
    {
        static void Main(string[] args)
        {
            string sampleEmailAddresses = @"john@email.com,jane@email.com,josh@email.com,jill@email.com";
            List<string> emailAddresses = sampleEmailAddresses.Split(new char[] { ',' }).ToList<string>();
            Console.WriteLine(emailAddresses.ToDelimitedString(",")); //Calling the extension method
            Console.Read();
        }
    }

    public static class Utils //Make sure this is static
    {
        public static string ToDelimitedString(this List<string> strings, string delimiter) //Defining the first parameter with the this keyword
        {
            return string.Join(delimiter, strings.ToArray());
        }
    }
}

For a more complete discussion, check out Scott Guthrie's blog:
http://weblogs.asp.net/scottgu/archive/2007/03/13/new-orcas-language-feature-extension-methods.aspx