Over a million developers have joined DZone.

Simplify Syntax with Extension Methods

DZone 's Guide to

Simplify Syntax with Extension Methods

· ·
Free Resource

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.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);
        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}$", 

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.


Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}