[Solved] In C, is single & and single | valid so as to avoid short circuit? Also please give some examples of utility of same in C# [closed]


Here are the answers to your questions:

Is & and | valid in C so that short circuit can be avoided?

No. The & and | operators in C mean different things compared to their C# logical counterparts.

In C, & and | are bitwise operators. They will evaluate both the sides and combine the bits of the resulting values according to the operator. Afterwards, if the resulting value is used in a logical context it will be processed as 0=false, everything else=true.

This is not the same as short-circuit logical operators as C# have.

In C# bool can only be true, false or null. Unlike C 0 is not false and all non-zero value is not true. So short circuit can never take place in C#.

So in C# what is the utility of & and |?

The purpose of & and | as logical operators in C# is to support non-short-circuit evaluation.

Take this example:

// s is string
if (s != null && s.Length > 0) { ... }

Here, if s is indeed null, the value of the first operand is false, hence the whole expression can never be true and thus the second operand, s.Length > 0 is not evaluated.

Contrast to this:

if (s != null & s.Length > 0) { ... }

Observe that I switched to the non-short-circuit & operator here. Here, if s is null, both operands will still be evaluated and the code will throw a NullReferenceException.

In some situations, it may be beneficial and required that you evaluate both sides even if you know the result will never be false regardless of what the second operand says. In those situations, you would use the non-short-circuit operators.


In C, the operators mean this:

  • | = bitwise OR operator
  • & = bitwise AND operator
  • || = logical OR operator that short circuits
  • && = logical AND operator that short circuits

In C#, the operators mean this:

  • | = bitwise OR operator if applied to integers, logical non-short-circuit OR operator if applied to bools
  • & = bitwise AND operator if applied to integers, logical non-short-circuit AND operator if applied to bools
  • || = logical OR operator that short circuits
  • && = logical AND operator that short circuits

solved In C, is single & and single | valid so as to avoid short circuit? Also please give some examples of utility of same in C# [closed]