The ternary operator (?:) in C# is a concise shorthand for an if-else statement
. It is officially called the conditional operator and is the only C# operator that takes three operands.
Syntax
- Condition: A Boolean expression that evaluates to
trueorfalse. - ?: Separates the condition from the "true" result.
- :: Separates the "true" result from the "false" result.
Basic Example
Instead of writing a multi-line
if-else block to assign a value, you can do it in a single line:Advanced Usage
- Nested Ternary: You can chain operators to handle multiple conditions (similar to
else if), though this can reduce readability if overused. - Conditional Ref: Since C# 7.2, you can use the ternary operator to return a reference to a variable rather than just its value.
- Method Calls: You can use ternary operators to decide which method to execute, provided both methods return the same type.
Best Practices
- Keep it Simple: Use it for simple assignments to improve code cleanliness.
- Avoid Deep Nesting: If logic becomes complex, a standard
if-elseorswitchis often easier to read and debug. - Type Matching: Both the true and false expressions must return the same type or be implicitly convertible to the same type.

