Is it worth to use method chaining in C#?

倾然丶 夕夏残阳落幕 提交于 2019-12-06 16:13:39

LINQ?

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

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.

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);
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!