Chaining methods with &&

流过昼夜 提交于 2019-12-10 15:57:10

问题


I have a bunch of methods that all return a bool.

If one method returns false then there is no value in calling the following methods, especially as some of them are 'expensive' operations.

Which is the more efficient?

bool result = method1();
if (result) result = method2();
if (result) result = method3();
return result;

or

return method1() && method2() && method3();

As I understand it, the 2nd form should stop evaluating as soon as one of the methods returns false, right?


回答1:


Yes you are right. Both && and || boolean operators in c# work as short-circuit operator. It stops evaluating expression once its value is determined. It stops unnecessary execution.

Hence return method1() && method2() && method3(); is better option in your case. If you have something in non-evaluated statement, say method3 in your case, it may lead to some side effects.

There is this very good language independent article about short-circuit operators on Wikipedia.

UPDATE: In C# if you want to use logical operator without short-circuit, use & and | operator instead.




回答2:


Yes, the two methods are equivalent. Using && is a shortcut to achieve the same result as using a backing variable.




回答3:


The second will stop the expression evaluation after the first expression is evaluated to false.

although both examples are semantically equivalent the second one is more readable in my opionion.



来源:https://stackoverflow.com/questions/8587109/chaining-methods-with

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