.NET Zone is brought to you in partnership with:

I'm a software developer working as a senior consultant at Kentor in Stockholm, Sweden. My core competence is as a technical specialist within development and system architecture. In my heart I am, and probably will remain, a programmer. I still think programming is tremendously fun, more than 20 years after I first tried it. That's why my blog is named Passion for Coding.  Anders is a DZone MVB and is not an employee of DZone and has posted 81 posts at DZone. You can read more from them at their website. View Full User Profile

Simplify Syntax with Extension Methods

05.16.2012
| 3195 views |
  • submit to reddit

Extension methods were first introduced with LINQ in C#3.0. They are just a syntactic construct, but as we’ll see in this post they can make a huge difference. What’s easier to read of these two?

string[] wishList1 =
    Enumerable.ToArray(
    Enumerable.Select(Enumerable.Where(Animals, a => a.StartsWith("A")),
    a => string.Format("I want a {0}.", a)));
 
string[] wishList2 = Animals.Where(a => a.StartsWith("A"))
    .Select(a => string.Format("I want a {0}.", a)).ToArray();

To me, the second alternative has several advantages:

  • Get rid of the name of the helper class declaring the method. Writing out the Enumerable class name doesn’t add any relevant information. On the contrary, it forces the reader to actively think of it to find out that it is irrelevant.
  • Left-to-right reading order instead of inside-out when following the evaluation order.
  • The method name and the parameters are written together. In the first example Select and the relevant code is splitted by the call to Enumerable.Where.

Extension methods creates a syntactic possibility to do two important things that are not allowed by the language.

  1. Add methods to existing classes.
  2. Add methods to interfaces.

Add Methods to Existing Classes

Sometimes it would be beneficial to extend existing classes with own methods. An example would be to add an IsEmail() method to the string class. The checking will be done using a regular expression, but using the name IsEmail makes the intent much more clear.

foreach (string s in strings)
{
    if (s.IsEmail())
    {
        Debug.WriteLine("{0} is a valid email address", (object)s);
    }
    else
    {
        Debug.WriteLine("{0} is not a valid email address", (object)s);
    }
}

An extension method is a static method of a static class with the first parameter marked with the this keyword. The IsEmail method is defined like this:

public static class Extensions
{
    public static bool IsEmail(this string str)
    {
        // Regex from http://www.regular-expressions.info/email.html
        return Regex.IsMatch(str, "^[A-Z0-9._%+-]+@[A-Z0-9.-]+\\.[A-Z]{2,4}$", 
            RegexOptions.IgnoreCase);
    }
}

Add Methods to Interfaces

Another powerful possibility with extension methods is to add methods to interfaces. The main example of this is the LINQ methods, that all operate on the IEnumerable<> interface. E.g. the Where method probably looks something like this.

public static IEnumerable<T> MyWhere<T>(
    this IEnumerable<T> source, Func<T, bool> filter)
{
    foreach (T t in source)
    {
        if (filter(t))
        {
            yield return t;
        }
    }
}

That’s some basic extension method examples. Next week I’ll show a couple of advanced techniques taking further advantage of extension methods.

Published at DZone with permission of Anders Abel, author and DZone MVB. (source)

(Note: Opinions expressed in this article and its replies are the opinions of their respective authors and not those of DZone, Inc.)