An addition to Solution 3: why "
flag2
is not even evaluated" can be important?
static bool Check1() { System.Console.WriteLine("checking condition 1"); return false; }
static bool Check2() { System.Console.WriteLine("checking condition 2"); return true; }
if (Check1() && Check2()) { }
if (Check1() & Check2()) { }
So, using '&&', instead of '&', "optimizes out" and redundant checks where it is possible. The difference is manifested with there is a
side effect in a Boolean operand.
In practice, I would advise:
- avoid using complex Boolean operation with any Boolean functions which may cause side effects;
- In case the above is taken into account, prefer '&&' and '||' over '&' or '|'.
—SA