The ternary operator
Learn to write a conditional expression in one line with ? :.
The ternary operator
To pick one of two values in a single line you use the ternary operator ? :: string m = age >= 18 ? "adult" : "child";.
First the condition, then ?, the value if true, :, and the value if false. It shortens simple two-way assignments; but nesting ternaries hurts readability, so keep them flat.
Ternary and null coalescing
For the case a variable might be null you use the ?? (null coalescing) operator: string name = input ?? "guest";. If input is null, 'guest' is taken.
This is much cleaner than writing input != null ? input : "guest". The ternary is general-purpose, ?? is specialized for null; both save the day for one-line picks.
Exercise Even or odd with the ternary
Declare an n variable with the value 8. Use the ternary operator to produce parity: if n % 2 == 0 then "even", otherwise "odd". Then print parity with Console.WriteLine.
Show example solution
"odd";
Example solution:
using System;
class Program
{
static void Main()
{
int n = 8;
string parity = n % 2 == 0 ? "even" : "odd";
Console.WriteLine(parity);
}
}
Test yourself
-
Complete the ternary separator
int n = 7; string parity = (n % 2 == 0) ____ "even" : "odd";Show answer
int n = 7; string parity = (n % 2 == 0) ? "even" : "odd"; -
Match each sign to its use
- ?
- Ternary true branch
- :
- Ternary false branch
- ??
- Null fallback value
- ?:
- Ternary pair
-
What is the result of 5 >= 3 ? "a" : "b"?
string r = 5 >= 3 ? "a" : "b";- "b"
- "ab"
- "a"
- Compile error
Show answer
"a" — Correct. 5 >= 3 is true, so 'a' is picked.