Fluent interfaces in C# – method chaining

For those of you who just tuned in, this is a third post on the subject of fluent interfaces using C#. In case you haven’t read them before – here are my previous posts on the subject:
Introduction
Extension Methods
Right, now that we’re familiar with fluent interfaces it’s time to move to “Method Chaining”.
Method chaining is the most recognized “fluent interface technique”. In fact it’s so popular that some believe it to be the only way to write a fluent API.
The idea behind method chaining is both simple and elegant – each method call returns an object that can be used to call another method that returns an object an so on.

Returning “this”

I guess that an example is in order – unless you’ve started writing .NET code yesterday you should be familiar with the StringBuilder class:
In situations where you need to perform repeated modifications to a string, the overhead associated with creating a new String object can be costly. The System.Text.StringBuilder class can be used when you want to modify a string without creating a new object. For example, using the StringBuilder class can boost performance when concatenating many strings together in a loop.
[From MSDN]
Using the StringBuilder class is simple:
var sb = new StringBuilder();
sb.Append("This is a simple list");
sb.AppendLine();
sb.Append("1. First item: ");
sb.Append(items[0]);
sb.AppendLine();
sb.Append("2. Second item: ");
sb.Append(items[1]);
The code above can also be written like this:
var sb = new StringBuilder()
    .Append("This is a simple list")
    .AppendLine()
    .Append("1. First item: ").Append(items[0])
    .AppendLine()
    .Append("2. Second item: ").Append(items[1]);
It’s up to you to decide which is more readable (#2) the fact is that writing the 2nd example is takes less time (try it), just keep using “.” after each method call.
The method chaining “trick” is in the return value of the method. In this case each method call above returns this at the end:
[SecuritySafeCritical]
public unsafe StringBuilder Append(string value)
{
    if (value != null)
    {
        // Here be code!
    }

    return this;
}
This means that we can invoke more methods on the same class one after the other.
Returning the same type on each method call means that the API is “stateless” – meaning that I can always choose the same methods regardless of the last method invoked.

Conclusion

In this post simple method chaining was introduced using return value of this in order to enable the user of the API to call the same class methods in one chain.
Keep in mind that this is only one technique - there are other ways to create fluent API that uses method chaining and I promise to write more about it in another post.

Happy coding…

Labels: , , ,