Pages

Topics

Tools

↑↓navigate↵openescclose
All guides

C# Ternary Operator: Syntax, Usage, and Pitfalls

Learn how to use the C# ternary operator for concise conditional assignments, avoid common pitfalls, and know when an if-else statement is the clearer choice.

~5 min readC#
#C##Ternary Operator#Conditional Operator#C# Syntax
Illustration of the C# ternary operator showing a conditional expression with true and false branches converging into a single result.

The C# ternary operator, also known as the conditional operator, evaluates a Boolean condition and returns one of two expressions based on the result. It is a compact alternative to an if-else statement when you need to assign a value or return a value conditionally. The operator is right-associative and has a lower precedence than most arithmetic and relational operators, which affects how expressions are parsed.

Ternary Operator Syntax

The syntax is straightforward:

csharp
condition ? consequent : alternative

The condition must be a Boolean expression. If it evaluates to true, the consequent expression is evaluated and becomes the result; otherwise, the alternative expression is evaluated. The branches must have compatible types: usually the same type, or one type must be implicitly convertible to the other. In C# 9 and later, when a target type is known, both branches can instead have implicit conversions to that target type.

Here is a minimal example:

csharp
int temperature = 25; string message = temperature > 20 ? "Warm" : "Cold";

This assigns "Warm" to message when temperature exceeds 20, and "Cold" otherwise. The ternary operator is an expression, so it can appear anywhere an expression is allowed, such as in assignments, return statements, and method arguments.

Using the Ternary Operator in Assignments

The most common use is conditional assignment. Consider a scenario where you need to pick a discount rate based on a customer's status:

csharp
double discount = isPremium ? 0.15 : 0.05;

You can also use it to return a value directly from a method:

csharp
public string GetStatus(bool isActive) { return isActive ? "Active" : "Inactive"; }

Because the ternary operator is an expression, you can chain it with other operations. For example, you can pass it as an argument:

csharp
Console.WriteLine(score >= 60 ? "Pass" : "Fail");

This keeps the code concise without introducing temporary variables. However, be careful not to overuse it in complex expressions where readability suffers.

Nested Ternary Operators and Readability

Ternary operators can be nested, but doing so often harms readability. Consider this example that selects a size label based on a numeric value:

csharp
string size = value < 10 ? "Small" : value < 20 ? "Medium" : "Large";

This works because the ternary operator is right-associative, so the expression is parsed as value < 10 ? "Small" : (value < 20 ? "Medium" : "Large"). While it is compact, most developers find nested ternaries harder to scan than an equivalent if-else chain. The logic becomes especially difficult when more than two conditions are involved.

A more readable alternative is a switch expression (the relational patterns in this example require C# 9.0 or later) or a traditional if-else chain:

csharp
string size = value switch { < 10 => "Small", < 20 => "Medium", _ => "Large" };

If you must nest ternaries, add parentheses to make the intended grouping explicit. But in practice, limit nesting to one level, and prefer other constructs for anything more complex.

Common Mistakes with the Ternary Operator

Several pitfalls can trip up developers new to the operator.

Type mismatch: The branches need a compatible type. Most of the time, one branch type must be implicitly convertible to the other. If neither type is convertible to the other, the expression does not compile. For example:

csharp
var result = condition ? 1 : "one"; // Error: no implicit conversion between int and string

Side effects: The ternary operator evaluates only the selected branch. This is usually desirable, but it means you cannot rely on both expressions being evaluated. If you need side effects in both branches, use an if-else statement instead.

Operator precedence: The ternary operator has lower precedence than most arithmetic and relational operators. For instance, x + y ? a : b is parsed as (x + y) ? a : b, not as x + (y ? a : b). If the condition contains other operators, add parentheses when they help make the intended grouping clear:

csharp
int result = (a + b) > 10 ? 1 : 2;

Using it as a statement: A conditional expression cannot be used as a statement by itself. You cannot write condition ? GetValue() : GetAlternative();. Assign the result or use it in a larger expression.

Ternary Operator vs if-else

The ternary operator and if-else are functionally equivalent for simple assignments, but they differ in expressiveness and readability. Use the ternary operator when you need a concise, inline conditional value. Use if-else when you need to execute statements, handle multiple conditions, or when the logic is too complex for a single expression.

ScenarioTernary Operatorif-else
Simple assignmentGoodVerbose
Multiple statementsNot possibleRequired
Complex branchingPoorBetter
ReadabilityDepends on contextUsually clearer

For example, this if-else block:

csharp
int max; if (a > b) { max = a; } else { max = b; }

can be replaced with:

csharp
int max = a > b ? a : b;

The ternary version is shorter, but the if-else version is more explicit. Choose based on your team's conventions and the surrounding code.

Performance and Runtime Behavior

From a runtime perspective, the ternary operator is not faster than an equivalent if-else assignment. Both forms produce a conditional branch, so the choice is about code style and readability, not speed.

One subtle runtime behavior is that only the selected branch is evaluated. This matters if the expressions have side effects or throw exceptions. For instance:

csharp
int value = condition ? GetValue() : throw new Exception("Invalid state");

If condition is false, GetValue() is never called. This can be useful for validating state, but it also means you cannot assume both branches are safe to evaluate.

Maintainability and Code Review Considerations

In code reviews, the ternary operator often sparks debate. Some teams favor it for its conciseness, while others avoid it because it can reduce readability, especially when nested or used in complex expressions.

A practical guideline is to use the ternary operator only when the condition and both branches are short and self-explanatory. If you need to add comments to explain what the expression does, an if-else statement is probably clearer. Also, be consistent with your codebase. If the existing code uses if-else for similar logic, follow that pattern.

Another consideration is debugging. A ternary operator is a single line, which can make it harder to set breakpoints on individual branches. If you need to inspect intermediate values, an if-else block gives you more granular control.

Ultimately, the ternary operator is a tool, not a rule. Use it where it improves clarity, and avoid it where it obscures intent. The best code is the code that your team can read and maintain without confusion.

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.