Ad space (banner)
#๏ธโƒฃC# Lessons
Lesson 15 / 68

The Ternary Operator

In this lesson you will learn how to use the ternary operator in C# to express a branch concisely on a single line. This is for anyone searching for "C# ternary operator how to use".

condition ? valueIfTrue : valueIfFalse expresses a simple if statement on one line. It suits short decisions such as working out whether someone counts as an adult and picking a message on the spot.

The sample code assigns a message to message based on age with the single line age >= 20 ? "Adult" : "Minor". Its biggest advantage is compressing something that would take several lines with an if statement into one.

A common stumbling block for beginners is over-using it until the code becomes harder to read. Cramming a complex condition in makes things worse, so the trick is to reserve it for simple either/or decisions.

In real-world development, nested ternary operators are especially hard to read, so knowing when to go back to an if statement matters.

๐Ÿ“– Reference code
โœ๏ธ Your code
Type your code, then press "Run"

๐Ÿงช This site can't compile or run C# directly, so it checks on the spot whether what you typed matches the reference code (scoring happens entirely in your browser โ€” nothing is sent anywhere).

Ad space (banner)
Ad space (in-article)