What is the correct way to chain methods in .Net

北慕城南 提交于 2019-12-06 03:43:46

In both cases you're using an extension method, returning an object, and then using that object as the input to the next method in the chain. The second example is close to a Fluent Interface (but not quite). I think in your two examples the critical distinction is one of mutability. Do you want the original input to be modified (the second example) or not (the first example)? The "correct" answer depends on the situation and context.

1) wins. Simon correctly answered that 2) wouldn't compile, but he did it as a comment, so I can't gie him credit for answering. The updated solution for 2) does everything as a side effect an I can't think of a reason why you would ever want to do that in a statically typed language.

The points made about chaining's debugging issue are something to consider, though I find chaining to be especially useful when filtering.

mybars.FilterByHasHappyHour() is much nicer than

BigGiantUtilityClass.GetBarsWithHappyHours(myBars)
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!