C# Ternary Operator: A Concise Guide to Conditional Expressions
C# Ternary Operator
Master the C# ternary operator for compact, readable conditional logic.
The ternary operator is a succinct replacement for simple if…else statements. Before diving in, review C#’s if…else syntax if you’re new to it.
Syntax:
Condition ? Expression1 : Expression2;
How it works:
- If
Conditionevaluates totrue,Expression1is returned. - If
Conditionevaluates tofalse,Expression2is returned.
Example: Convert a multi‑line if…else into one line.
if (number % 2 == 0)
{
isEven = true;
}
else
{
isEven = false;
}
to:
isEven = (number % 2 == 0) ? true : false;
Why “ternary”?
It operates on three operands: the condition, the true branch, and the false branch.
Example 1: Basic Usage
using System;
namespace Conditional
{
class Ternary
{
public static void Main(string[] args)
{
int number = 2;
bool isEven;
isEven = (number % 2 == 0) ? true : false;
Console.WriteLine(isEven);
}
}
}
Output:
True
In this program, number is 2, so the condition evaluates to true, yielding isEven = true. The ternary can also return other types—strings, numbers, characters—making it versatile.
Directly printing the result is also possible:
Console.WriteLine((number % 2 == 0) ? true : false);
When to Use the Ternary Operator
The ternary operator is ideal for short, clear conditions. Overusing it can reduce readability, especially with nested expressions.
For example, a chain of if…else if can be condensed:
if (a > b)
{
result = "a is greater than b";
}
else if (a < b)
{
result = "b is greater than a";
}
else
{
result = "a is equal to b";
}
to a single line:
result = a > b ? "a is greater than b" : a < b ? "b is greater than a" : "a is equal to b";
While this shortens the code, nested ternaries can become hard to follow. Use them sparingly for simple conditions; keep more complex logic in explicit if blocks.
C Language
- C# Operators – Comprehensive Guide to Operators in C#
- Mastering C# Operator Precedence & Associativity: A Practical Guide
- Master C++ Operator Overloading: Practical Examples & Best Practices
- Mastering Operator Overloading in Python: A Practical Guide
- Java instanceof Operator: A Comprehensive Guide
- C++ Operator Overloading – A Practical Guide with Code Examples
- Mastering C++ Overloading: Functions & Operators Explained
- Master MATLAB Basics: Essential Syntax & Commands
- Mastering Operator Overloading in C# for Custom Types
- Role of a 3D Printer Operator: Skills, Responsibilities, and Career Opportunities