The Ternary Operator
The ternary operator is a short one-line choice: 'is it raining? take an umbrella, otherwise take sunglasses'. It picks between two values without a full if-else.
In this page:
Syntax
type result = condition ? valueIfTrue : valueIfFalse;
The Ternary Operator
The ternary operator condition ? valueIfTrue : valueIfFalse is a compact one-line alternative to a simple if/else. It always evaluates to exactly one of its two branches. Ternary expressions can be nested but doing so hurts readability quickly.
Note:
Use ternary for short, simple value selection — fall back to
if/else once logic gets complex.Example: The Ternary Operator
using System;
class Program
{
static void Main(string[] args)
{
int age = 16;
string status = age >= 18 ? "adult" : "minor";
Console.WriteLine(status);
Console.WriteLine(age % 2 == 0 ? "even" : "odd");
}
}
Login to try C/C++/Java/PHP code in the editor
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the
view already swaps in the hi_ translation fields (or blanks these
out if untranslated), so this renders correctly for both languages
without a lang_code check here. #}
Common Mistakes
- Nesting several
?:operators so the code becomes hard to read. - Using branches of different types that have no common type, which is a compile error.
- Using the ternary operator as a statement instead of an expression, such as
x > 0 ? Print() : Skip();.
🔒
Chapter Quiz — Complete all 6 topics to unlock
0/6 topics done
Complete these topics first: