Simplify Syntax with Extension Methods

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.
Software Development is a Job – Coding is a Passion

I'm Anders Abel, an independent systems architect and developer in Stockholm, Sweden.

profile for Anders Abel at Stack Overflow, Q&A for professional and enthusiast programmers

Code for most posts is available on my GitHub account.

Popular Posts

Archives

Series

Powered by WordPress with the Passion for Coding theme.