C#

Logical Operators in C#: Short-Circuiting, Eager Evaluation and Nullable bool

Nick Cosentino (Dev Leader)
C#

A walk through C# logical operators for built-in `bool` and `bool?` operands: when the second operand is skipped, why `&` and `|` still evaluate both sides, and how null fits into three-valued logic.

Key points

  • Conditional `&&` skips the right operand when the left side is already false, making it a natural guard for null checks and parses.
  • Plain `&` and `|` evaluate both operands on normal completion, so swapping them for `&&` and `||` can silently drop side effects.
  • `bool?` uses three-valued logic: false AND unknown is false, true OR unknown is true, but true AND null and false OR null stay null.
  • Conditional `&&` and `||` cannot take `bool?` operands; you must pick a policy such as `== true` or a default false value.
  • Precedence puts negation tightest and `&&` above `||`, so mixed access rules need parentheses to make the intended policy visible.
  • Extension members in C# 14 add operator support, but the predefined bool and nullable bool rules still apply unchanged.

Real-world use

  • A validation pipeline that parses user input and only range-checks the number after a successful `int.TryParse`.
  • An authorization check like 'administrator or active verified account', where wrong grouping would open the wrong access path.
  • A form or sensor model where an unanswered field arrives as `bool?` and you must decide what null means before combining conditions.
  • Code review of legacy if-statements that use `&` for two independent checks which were deliberately meant to both run.

This summary was generated by the agent from the original post on Nick Cosentino (Dev Leader). The full text and all rights belong to its author and publisher. Go to original

Report this story

Is something wrong with the summary, or do you own this content? Your message comes straight to my inbox.

Type of message

Related stories

Feedback

Found a bug or have an idea? Your message lands straight in my inbox.

Type of message