Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<blockquote> <p>In terms of coding practice which is the better to use and why?</p> </blockquote> <p>Simple answer: always use the short-circuited versions. There’s simply no reason not to. Additionally, you make your code clearer because you express your <em>intent</em>: logical evaluation. Using the bitwise (logical) operations implies that you want just that: bit operations, not logical evaluation (even though the MSDN calls them “logical operators” as well, when applied to boolean values).</p> <p>Additionally, since short-circuiting only evaluates what needs evaluating, it’s often faster, and it allows to write such code as</p> <pre><code>bool nullorempty = str == null || str.Length == 0; </code></pre> <p>(Notice that to solve this particular problem a better function already exists, namely <code>string.IsNullOrEmpty</code> which you also used in your question.) This code wouldn’t be possible with the bitwise logical operations because even if <code>str</code> were <code>null</code>, the second expression would get evaluated, resulting in a <code>NullReferenceException</code>.</p> <p><strong>EDIT</strong>: If you <em>want</em> side-effects to occur in a logical context please <em>still</em> don’t use bitwise operations. This is a typical example of being too clever. The next maintainer of the code (or even yourself, after a few weeks) wo sees this code will think “hmm, this code can be cleared up to use conditional operators,” thus inadvertedly breaking the code. I pity whoever is in charge of fixing this bug.</p> <p>Instead, if you have to rely on side, effects, make them explicit:</p> <pre><code>bool hasBuzzed = checkMakeBuzz(); bool isFrobbed = checkMakeFrob(); bool result = hasBuzzed || isFrobbed; </code></pre> <p>Granted, three lines instead of one. But a much clearer code as a result.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload