It's always existed in C# and indeed in any C-style oo language (eh, most popular C-style language except C itself!)
It's unfair to compare it the the VB6 With...End With
syntax, as it's much clearer what is going on in this case (about the only good thing I have to say about VB6's With...End With
is at least it isn't as bad as Javascripts since it requires prior dots).
It is as people have said, a combination of the "fluent interface" and the fact that the .
operator allows for whitespace before and after it, so we can put each item on newlines.
StringBuilder
is the most commonly seen case in C#, as in:
new StringBuilder("This")
.Append(' ')
.Append("will")
.Append(' ')
.Append("work")
.Append('.');
A related, but not entirely the same, pattern is where you chain the methods of an immutable object that returns a different object of the same type as in:
DateTime yearAndADay = DateTime.UtcNow.AddYears(1).AddDays(1);
Yet another is returning modified IEnumerable<T>
and IQueryable<T>
objects from the LINQ related methods.
These though differ in returning different objects, rather than modifying a mutable object and returning that same object.
One of the main reasons that it is more common in C++ and Java than in C# is that C# has properties. This makes the most idiomatic means of assigning different properties a call to the related setter that is syntactically the same as setting a field. It does however block much of the most common use of the fluent interface idiom.
Personally, since the fluent interface idiom is not guaranteed (there's nothing to say MyClass.setProp(32)
should return this
or indeed, that it shouldn't return 32
which would also be useful in some cases), and since it is not as idiomatic in C#, I prefer to avoid it apart from with StringBuilder
, which is such a well-know example that it almost exists as a separate StringBuilder
idiom within C#