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();
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.