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
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

Fluent Interfaces in C# – Extension Methods

Dror Helper user avatar by
Dror Helper
·
Jul. 17, 12 · Interview
Like (0)
Save
Tweet
Share
5.94K Views

Join the DZone community and get the full member experience.

Join For Free

For those of you who haven't read the previous post. This post is the 2nd of many where I explain how to use C# and a bag of tricks to create fluent interfaces – easily.

In the previous post I’ve talked about what fluent interfaces is all about and gave a brief introduction to the subject – in this post we’ll actually get to see some code.

The introduction you might not need

Extension methods enable you to "add" methods to existing types without creating a new derived type, recompiling, or otherwise modifying the original type. Extension methods are a special kind of static method, but they are called as if they were instance methods on the extended type. For client code written in C# and Visual Basic, there is no apparent difference between calling an extension method and the methods that are actually defined in a type.

from C# Programming Guide

First introduced in .NET 3 – extension methods have been widely used to “add” methods to existing class without changing the actual class implementation. Using extension methods is as simple as creating a static method – in fact that’s all it takes.

Using extension methods to create an API

The quick and simple way to create “poor man’s” fluent API is to use Extension methods.

All we need is to create a few static methods and we can transform the following code:

// Instead of using this:
DateTime.Now.AddDays(14);

// Using extension method we can write:
DateTime.Now.AddWeeks(2);

// Or even this:
14.DaysFromNow();

The actual implementation is quite simple – but here it is just in case:

public static DateTime AddWeeks(this DateTime baseTime, int weeks)
{
    return baseTime.AddDays(7 * weeks);
}

public static DateTime DaysFromNow(this int days)
{
    return DateTime.Now.AddDays(days);
}

Thus by using simple method call we managed to transform “14” to “two weeks” – not much but it’s a good place to start.

When to use

Extension methods are best used when the API we’re trying to add is on top some 3rd party component or internal class we do not wish to use.

This method is very effective when using along with “method chaining” where using extension method is a good starting point for the whole API – but more on that in posts to come.

In the meantime keep in mind that one of the best fluent API out there (in my humble opinion) uses extension method extensively:

public static IEnumerable<TSource> Where<TSource>
                               (this IEnumerable<TSource> source,
                                Func<TSource, bool> predicate)


public static IEnumerable<TResult> Select<TSource, TResult>
                                (this IEnumerable<TSource> source,
                                 Func<TSource, TResult> selector)

Cons and pitfalls

There are some problems in “adding methods” to existing class – especially if this class is part of the CLR. In the example above I’ve used extension method on integer to create a new DateTime which has nothing to do with the previous type. I’ve added as method to every single integer in my system. Although I could filter the the use of the new method using namespace it’s still a lot of noise.

Conclusion

This is it – the first tool in your fluent interface belt. Experiment with it and use it wisely. And as always:

Happy Coding.

Interface (computing) Extension method

Published at DZone with permission of Dror Helper, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

Popular on DZone

  • API Design Patterns Review
  • A Brief Overview of the Spring Cloud Framework
  • How Observability Is Redefining Developer Roles
  • Upgrade Guide To Spring Data Elasticsearch 5.0

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: