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
Refcards Trend Reports Events Over 2 million developers have joined DZone. Join Today! Thanks for visiting DZone today,
Edit Profile Manage Email Subscriptions Moderation Admin Console How to Post to DZone Article Submission Guidelines
View Profile
Sign Out
Refcards
Trend Reports
Events
Zones
Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Partner Zones AWS Cloud
by AWS Developer Relations
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Partner Zones
AWS Cloud
by AWS Developer Relations
  1. DZone
  2. Coding
  3. JavaScript
  4. Simplify Syntax with Extension Methods

Simplify Syntax with Extension Methods

Anders Abel user avatar by
Anders Abel
·
May. 16, 12 · Interview
Like (0)
Save
Tweet
Share
4.25K 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

  • Steel Threads Are a Technique That Will Make You a Better Engineer
  • Tracking Software Architecture Decisions
  • gRPC on the Client Side
  • Authenticate With OpenID Connect and Apache APISIX

Comments

Partner Resources

X

ABOUT US

  • About DZone
  • Send feedback
  • Careers
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • 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: