Monday, May 4, 2026

C# short circuiting and non-short-circuiting operators

 In C#, short-circuiting refers to the behavior where the second operand of a logical expression is evaluated only if the first operand doesn't already determine the final result. 

Short-Circuiting Operators
These operators are formally known as conditional logical operators
  • && (Conditional AND): If the left-hand operand is false, the overall result must be false, so the right-hand operand is not evaluated.
  • || (Conditional OR): If the left-hand operand is true, the overall result must be true, so the right-hand operand is not evaluated.
  • ?. and ?[] (Null-conditional): These "short-circuit" by returning null immediately if the operand to the left is null, preventing the evaluation of the rest of the member access chain.
  • ?? (Null-coalescing): Evaluates the right-hand operand only if the left-hand operand evaluates to null. 
Non-Short-Circuiting Operators
These operators always evaluate both operands, regardless of the result of the first one. 
  • & (Logical AND): When used with bool operands, it computes the logical AND but always evaluates both sides.
  • | (Logical OR): When used with bool operands, it computes the logical OR but always evaluates both sides.
  • ^ (Logical Exclusive OR): Always evaluates both operands to determine if exactly one is true. 

No comments:

Post a Comment

Python List, NumPy Array and Pandas DataFrame

 The strength of numpy arrays is that it allows for vectorized operations (applying a calculation to the whole array at once without loops)...