0
0
C Sharp (C#)programming~5 mins

Ternary conditional operator in C Sharp (C#) - Cheat Sheet & Quick Revision

Choose your learning style9 modes available
Recall & Review
beginner
What is the ternary conditional operator in C#?
It is a shorthand way to write an if-else statement using the syntax: condition ? value_if_true : value_if_false;
Click to reveal answer
beginner
How does the ternary operator improve code readability?
It makes simple conditional assignments or returns concise and easy to read by reducing multiple lines into one line.
Click to reveal answer
beginner
Write a ternary expression to assign 'status' as "Adult" if age is 18 or more, otherwise "Minor".
string status = age >= 18 ? "Adult" : "Minor";
Click to reveal answer
intermediate
Can the ternary operator be nested in C#? If yes, how?
Yes, you can nest ternary operators by placing another ternary expression in either the true or false part, but it can reduce readability.
Click to reveal answer
intermediate
What types of expressions can be used with the ternary operator?
Any expressions that return a value compatible with the variable or context where the ternary operator is used.
Click to reveal answer
What does the ternary operator syntax look like in C#?
Aif (condition) { value_if_true } else { value_if_false }
Bcondition ? value_if_true : value_if_false
Ccondition ? value_if_false : value_if_true
Dcondition : value_if_true ? value_if_false
Which of these is a valid use of the ternary operator?
Aint max = a > b : a ? b;
Bint max = a > b if a else b;
Cint max = a > b then a else b;
Dint max = a > b ? a : b;
What will this code output? int x = 5; string result = x > 10 ? "Big" : "Small"; Console.WriteLine(result);
A"Small"
BError
C5
D"Big"
Is it recommended to use nested ternary operators?
AYes, always for clarity
BOnly if you use more than three conditions
CNo, it can make code hard to read
DOnly in loops
Which data types can be used with the ternary operator?
AAny type as long as both outcomes are compatible
BOnly integers
COnly booleans
DOnly strings
Explain how the ternary conditional operator works and give a simple example.
Think of it as a short if-else in one line.
You got /5 concepts.
    Describe when it is better to use the ternary operator instead of a full if-else statement.
    Use it for quick decisions, not complicated logic.
    You got /4 concepts.