C# uses short-circuit evaluation, so performance wise, both should be identical.
In a language which does not have short-circuit evaluation, the latter would probably be more efficient, but as with all optimisation, you should benchmark to see if there is a performance gain, and decide if that gain is worth making the code significantly more complex and less maintainable.
Also, it is possible that an 'optimisation' like this might not actually be an optimisation. If the conditions are cheap, and the extra complexity increases the size of the code so that it is now (for instance) no longer fits in the cache, it may actually perform less well!
From a coding style point of view, this should really be driven by what you want to do with the else
's. If you want to do one thing if all are true and another thing when any is false, pick the former. If you want to be able to do different things depending on which conditions are false, user the latter.
It's not really a matter of style, it's a matter of what you want to achieve. Certainly though, if you want to do the same thing if any are false, you should be using the first form, so you don't end up with the same repeated code in each one of the else blocks. If in doubt, given two ways to implement the same requirement, it is always a good idea to chose the simplest, clearest, most maintainable option.
Oh, just in case you don't know, if you want to eagerly evaluate conditions in C#, you can use &
and |
instead of &&
and ||
. So, if you want all conditions to run (perhaps for the side effects), you can do:
if (CND1 & CND2 & CND3 & CND4) { // Eagerly evaluate all conditions.
...
}
else {
...
}
One thing to bear in mind here though, is that this does look very similar to the short-circuited version, so it is well worth commenting it, especially if C or C++ people are likely to be looking at the code.
Also, I find the following lazy construct quite useful:
ok = ok && CND;
But the strict equivalent looks far too similar:
ok = ok & CND;
As such, I make sure that code like this is re-factored to:
ok &= CND;
Which makes the difference in behaviour much more obvious.