Pages

Topics

Tools

↑↓navigate↵openescclose
All guides

C# && and || Operators Explained for Conditionals

Understand how C# && (AND) and || (OR) work in conditionals, including short-circuit evaluation, operator precedence, nullable Booleans, and common pitfalls to avoid.

~5 min readC#
#C##logical operators#short-circuit#conditional expressions
Diagram showing C# logical AND and OR operators with short-circuit evaluation paths.

In C#, the && and || operators let you combine multiple Boolean conditions into a single conditional expression. They are used in if statements, while loops, and anywhere a Boolean expression is expected. For example, the following code checks that a collection has at least one element and that the first element is non-null:

csharp
if (items.Length > 0 && items[0] != null) { // Process the first item. }

This article explains how these logical AND and OR operators behave at runtime, why short-circuit evaluation matters, and what mistakes to avoid when writing conditionals.

How && and || Evaluate to a Boolean

Both && and || are logical operators that combine two Boolean expressions into one result. The AND operator (&&) evaluates to true only when both operands are true. The OR operator (||) evaluates to true when at least one operand is true. The following table summarizes the truth tables for both operators.

| Left operand | Right operand | left && right | left || right | | ------------ | ------------- | --------------- | --------------- | | true | true | true | true | | true | false | false | true | | false | true | false | true | | false | false | false | false |

Both operators are binary operators, meaning they take two operands. If you need to combine more than two conditions, you chain them: a && b && c. The expression is evaluated left-to-right, and the result is true only if every condition in the chain is true.

Short-Circuit Evaluation in C#

The most important runtime behavior of && and || is short-circuiting. C# evaluates the left operand first, then decides whether the right operand needs to be evaluated. For &&, if the left operand is false, the entire expression is false regardless of the right operand, so the right operand is not evaluated. Conversely, for ||, if the left operand is true, the entire expression is true, and the right operand is skipped.

This behavior prevents unnecessary work and, more critically, avoids exceptions in cases where evaluating the right operand would be invalid. A common example is checking for null before accessing a member:

csharp
string? name = GetName(); if (name != null && name.Length > 0) { Console.WriteLine(name); }

When name is null, the left operand (name != null) is false, so the right operand (name.Length > 0) is never evaluated. Without short-circuiting, this code would throw a NullReferenceException. The same principle applies to ||, where the right-hand check is skipped if the left check is already true:

csharp
string value = GetValue() ?? "fallback"; if (value.Length > 0 || IsFallbackAllowed()) { // Process value. }

If value.Length > 0 is true, the call to IsFallbackAllowed() is never made. This can be useful when the right operand calls an expensive method or has side effects you want to avoid.

Conditional Operator vs. Boolean Operators

C# also provides a ternary conditional operator (?:) that is not the same as && or ||. The ternary operator returns a value based on a condition, as in var result = condition ? first : second;. The && and || operators only produce a Boolean result; they cannot directly yield a value such as an integer or string. However, you can use && and || to build a Boolean condition that then drives a ternary decision. For example:

csharp
int score = 85; string grade = (score >= 90 && score <= 100) ? "A" : "B";

Here the && operator evaluates the score range, and the ternary operator selects between two strings. This shows how logical operators fit into larger expressions, but they remain strictly Boolean.

Operator Precedence and Parentheses

C# defines precedence rules for operators. && has higher precedence than ||, which means a || b && c is parsed as a || (b && c), not (a || b) && c. This can lead to subtle bugs if you assume left-to-right grouping. For instance:

csharp
bool isValid = name != null && name.Length > 0 || allowEmpty;

This is equivalent to (name != null && name.Length > 0) || allowEmpty. If allowEmpty is true, the expression is true even when name is null. If you intended the OR to apply only to the length check, you must add parentheses:

csharp
bool isValid = name != null && (name.Length > 0 || allowEmpty);

Now the AND requires both name != null and either name.Length > 0 or allowEmpty. Parentheses make the intent explicit and prevent confusion. As a rule, when mixing && and ||, use parentheses to clarify the grouping—both for the compiler and for other developers reading the code.

Common Mistakes and Pitfalls

One frequent mistake is using the single & and | operators when && and || are intended. The single forms always evaluate both operands. With integer operands they perform bitwise operations; with Boolean operands they perform logical operations but without short-circuiting. For example:

csharp
if (user != null & user.IsActive) // wrong

Here, even if user is null, the right operand user.IsActive is evaluated, causing a NullReferenceException. Using && instead avoids that. Single & and | have their place—such as when working with bit flags—but for conditionals, always use && and ||.

Another issue is overcomplicating conditions. For example, if ((x > 0) && (x > 0)) is redundant. More subtly, for a non-nullable bool, conditions like if (x == true) are verbose; use if (x) directly. Also, be cautious when mixing negation: if (!(x > 0) || y == 0) can often be simplified, but ensure you preserve the logic.

Practical Usage for Incoming Data Validation

A common real-world use of && and || is validating incoming data, such as parsing a configuration or checking user input. The short-circuit behavior lets you safely combine checks that depend on previous ones. For example:

csharp
bool TryParseConfig(string input, out int threshold) { threshold = 0; if (input != null && input.Length > 0 && int.TryParse(input, out threshold)) { return threshold > 0; } return false; }

Here, each condition builds on the previous one: if input is null, the method exits early. If it is non-null but empty, it exits. Only when a non-empty string exists does the parser run. This avoids calling int.TryParse unnecessarily; note that int.TryParse would not throw if passed null, so the main benefit is skipping the parse when the input is clearly unusable.

The same pattern applies to OR when you want to accept multiple valid formats:

csharp
if (format == "json" || format == "xml") { // Parse based on format. }

These operators are the building blocks of robust validation logic.

When the Right Operand Has Side Effects

Because short-circuiting may skip the right operand, you must not rely on side effects of that operand. If the right operand calls a method that performs a database write, logging, or increments a counter, the behavior becomes dependent on the left operand's value. Consider this example:

csharp
bool SendNotification() { // Sends an email or writes to a queue. return true; } if (isUserActive && SendNotification()) { // Log success. }

If isUserActive is false, SendNotification() is never called, and no notification is sent. If the intent is to always call the method, separate the calls:

csharp
bool notificationSent = SendNotification(); if (isUserActive && notificationSent) { // Log success. }

This makes the side effect explicit and independent of the condition. Avoid embedding operations with side effects directly inside a conditional expression unless you fully understand the short-circuit consequence.

Nullable Booleans and the Null-Conditional Operator

C# supports bool? (nullable Boolean) which can have values true, false, or null. The && and || operators do not accept nullable Boolean operands directly; an expression such as isActive && true does not compile. Instead, handle the null case explicitly. For example:

csharp
bool? isActive = GetStatus(); if (isActive == true) { // Only when explicitly true. } if (isActive != false) { // This is true when isActive is null or true. }

Using == true is a common pattern to treat null as false. The null-conditional operator (?.) is different again; it short-circuits property access and returns null if the receiving object is null. You might combine it with a comparison to check both non-null and a property:

csharp
if (user?.IsActive == true) { // user is non-null and IsActive is true. }

In this case, user?.IsActive returns null when user is null, and the comparison == true handles it correctly. This is a compact form of a null check plus a logical condition, but it does not use && directly.

Summary of Key Behaviors

Understanding && and || in C# comes down to three core points: they produce Boolean results, they short-circuit evaluation, and their precedence can change meaning. You should always use && and || for logical conditions, avoid single & and | in conditionals, and add parentheses when mixing operators. When the right operand has side effects, move that logic out of the expression. These rules will help you write conditionals that are correct, easy to read, and safe from null-reference errors.

Try matching browser tools

All tools

Small utilities that fit C# work — they run entirely in this browser tab, so nothing you paste leaves your device.

All C# guides

More in C#

All C# guides

The guides filed next to this one in C#, in library order.