Having Collection initializers in C# and being allowed to define properties of a class without having to call the constructor, is there any point in using Method Chaining in C#? I can't see any. Maybe I'm missing something here?
Thanks
Having Collection initializers in C# and being allowed to define properties of a class without having to call the constructor, is there any point in using Method Chaining in C#? I can't see any. Maybe I'm missing something here?
Thanks
A common use is fluent interfaces
EDIT: In response to the questions in the comments, property/collection initialisers are fairly limited in that you can only set propeties or call the Add method on a collection, whereas method calls are more flexible since they can take multple arguments.
A fluent interface is just one specific use of method chaining to produce a more readable API, often for object builders.
Also, as an aside that MSDN article is quite misleading since object initialisers don't allow you to bypass the constructor, it's just that in the example, the StudentName
class has a default constructor which does nothing.
LINQ?
var item = sequence.Where(x => x.Age > 100)
.Select(x => new { x.FirstName, x.LastName })
.OrderBy(x => x.LastName)
.FirstOrDefault();
CuttingEdge.Conditions is a good example of why method chaining is convenient?
public void GetData(int? id)
{
// Check all preconditions:
Condition.Requires(id)
.IsNotNull()
.IsInRange(1, 999)
.IsNotEqualTo(128);
}