Logical Operators vs Conditional Logical Operators in C#

Logical Operators vs Conditional Logical Operators in C#

You probably already know this, but there is a difference between the logical operators (| and &) and the conditional logical operators (|| and &&). The difference is conditional logical operators short circuit but the logical operators do not. Here’s an example.

Assume we have the following two methods that check if an “animal” is “a cat” or “a dog”. For this example IsCat is hard-coded to return true and IsDog is hard-coded to throw an exception, i.e.

  public bool IsCat(string animal)
  {
      return true;
  }

  public bool IsDog(string animal)
  {
      throw new NotImplementedException();
  }

Given these methods if we use the conditional-OR operator (||) then the following snippet will run and print the expected message:

  var animal = "cat";
  if (IsCat(animal) || IsDog(animal))
  {
      Console.Out.WriteLine("Animal is a cat or a dog");
  }

The above code runs because the conditional-OR operator short circuits and stops after evaluating the first part of the OR expression since it already knows the expression will evaluate to true.

The logical OR operator (|) on the other hand does not short circuit so the next code snippet using the logical OR operator will fail at runtime with an exception:

  var animal = "cat";
  if (IsCat(animal) | IsDog(animal))
  {
      Console.Out.WriteLine("Animal is a cat or a dog");
  }

For a more succinct explanation and possibly clearer example, see the C# documentation for || operator on MSDN[1].


Links:

  1. || Operator (C# Reference) on MSDN.

Leave a comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.