C# Instances where single bar | operator and double bar || operator's use would effect code

Viewed 151

I understand that single bar evaluates both sides regardless and double bar only evaluates the right sided conditional if the left side evaluates to false but I can't in my right mind find any instances where the variation in use would have an effect on my code.

Does anyone have any visual examples to help me better understand if there is any significance in this difference between these operators?

2 Answers

Consider the following code:

public static void Main()
{
    string test = null;

    if (test == null || test.Length == 0) // Doesn't crash.
        Console.WriteLine("A");

    if (test == null | test.Length == 0) // Does crash.
        Console.WriteLine("B");
}

The second if will crash because it will try to evaluate test.Length when test is null.

And anything where the code after the | has side-effects will have different results, of course.

For example, this prints 1:

int value = 0;

if (value == 0 | ++value == 0)
    Console.WriteLine(value);

And this prints 0:

int value = 0;

if (value == 0 || ++value == 0)
    Console.WriteLine(value);

An example could be bool IEnumerator.MoveNext()

It does two things:

  • Advances the enumerator to the next element of the collection.
  • returns a bool: "true if the enumerator was successfully advanced to the next element; false if the enumerator has passed the end of the collection."

A usuall way to process Emuerators is while(EnumeratorInstance.MoveNext()). But if you add a 2nd condition that is checked first, like continueEnumerating == true you would get different results - namely the Enumerator advancing even if you do not need to.

Note that overall in my experience the single variant is less common exactly because it incurs side effects. For clarity if I want both sides to execute, I would use bool moreStuffToRead = EnumeratorInstance.MoveNext(); and then check for both bool values with a ||. But that is just personal preference. I value understandable code above all else, even performance.

Related