This is a mirror of official site: http://jasper-net.blogspot.com/

Simplify Syntax with Extension Methods

| Thursday, May 17, 2012
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.

Add methods to existing classes.
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);
    }
}

Read more: Passion for Coding
QR: Inline image 1

Posted via email from Jasper-net

0 comments: