Chain Methods Using &&

I have a bunch of methods that return bool.

If one method returns false, then calling the following methods does not have a value, especially if some of them are "expensive" operations.

What is more effective?

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

or

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

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

+4
source share
3 answers

Yes you are right. And && and || Boolean operators in C # act as a short circuit operator . He ceases to evaluate the expression after determining its value. It stops unnecessary execution.

Therefore, return method1() && method2() && method3(); - the best option in your case. If you have something in an underrated statement, say method3 in your case, this can lead to some side effects.

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

UPDATE: In C #, if you want to use a logical operator without a short circuit, use and and | the operator.

+9
source

Yes, these two methods are equivalent. Using && is a shortcut to achieving the same result as using a reverse gear variable.

+1
source

The second stops evaluating the expression after the first expression evaluates to false.

although both examples are semantically equivalent, the second is more readable in my description.

0
source

Source: https://habr.com/ru/post/1387336/


All Articles