DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
  • Refcardz
  • Trend Reports
  • Webinars
  • Zones
  • |
    • Agile
    • AI
    • Big Data
    • Cloud
    • Database
    • DevOps
    • Integration
    • IoT
    • Java
    • Microservices
    • Open Source
    • Performance
    • Security
    • Web Dev
DZone >

Simplify Syntax with Extension Methods

Anders Abel user avatar by
Anders Abel
·
May. 16, 12 · · Interview
Like (0)
Save
Tweet
4.07K Views

Join the DZone community and get the full member experience.

Join For Free

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.

Extension method Syntax (programming languages) Interface (computing) Advantage (cryptography) Evaluation Strings Clear (Unix)

Opinions expressed by DZone contributors are their own.

Popular on DZone

  • Application Scalability — How To Do Efficient Scaling
  • The Right Way to Hybridize Your Product Development Technique
  • What SREs Can Learn From the Atlassian Nightmare Outage of 2022
  • 10 Steps to Become an Outstanding Java Developer

Comments

Partner Resources

X

ABOUT US

  • About DZone
  • Send feedback
  • Careers
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • MVB Program
  • Become a Contributor
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 600 Park Offices Drive
  • Suite 300
  • Durham, NC 27709
  • support@dzone.com
  • +1 (919) 678-0300

Let's be friends:

DZone.com is powered by 

AnswerHub logo