views:

116

answers:

3

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

+5  A: 

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.

Lee
I am not asking what are their common uses, I'm if there is any point in using the "old" method chaining in C# as you have both collection and property initializers.
devoured elysium
@devoured elysium: Perhaps you need to tell us what you consider the "old" method chaining to be.
LukeH
http://en.wikipedia.org/wiki/Method_chaining
devoured elysium
btw, what really is the difference between method chaining and fluent interfaces?
devoured elysium
@Lee: +1 for calling out the misleading MSDN article. I was about to do the same.
LukeH
Yes, I know the constructor thing is misleading, but I was lazy to be more objective :(
devoured elysium
+5  A: 

LINQ?

var item = sequence.Where(x => x.Age > 100)
                   .Select(x => new { x.FirstName, x.LastName })
                   .OrderBy(x => x.LastName)
                   .FirstOrDefault();
LukeH
+3  A: 

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);
}
Steven
Good example, indeed.
devoured elysium