The ternary conditional operator lets you choose between two values quickly based on a condition. It makes your code shorter and easier to read when you have simple decisions.
When you want to assign a value based on a simple yes/no question.
When you want to print different messages depending on a condition.
When you want to return one of two values from a method quickly.
When you want to replace a short if-else statement with cleaner code.
Syntax
C Sharp (C#)
condition ? value_if_true : value_if_false;
The condition is a boolean expression that is either true or false.
If the condition is true, the operator returns value_if_true, otherwise it returns value_if_false.
Examples
Assigns the greater of a or b to max.
C Sharp (C#)
int max = (a > b) ? a : b;
Sets result to "Pass" if score is 60 or more, otherwise "Fail".
C Sharp (C#)
string result = (score >= 60) ? "Pass" : "Fail";
Prints a message depending on whether isSunny is true or false.
Hint: Always include ':' between true and false parts [OK]
Common Mistakes:
Forgetting the colon ':'
Adding extra quotes or commas
Misplacing parentheses
5. Given a list of integers, which C# code snippet correctly uses the ternary operator to create a new list of strings labeling each number as "Positive" or "Non-positive"?
hard
A. var labels = numbers.Select(n => n > 0 ? "Positive" : "Non-positive").ToList();
B. var labels = numbers.Select(n => n > 0 ? "Positive" "Non-positive").ToList();
C. var labels = numbers.Select(n => if (n > 0) "Positive" else "Non-positive").ToList();
D. var labels = numbers.Select(n => n > 0 ? "Positive" : ).ToList();
Solution
Step 1: Understand the use of ternary operator inside LINQ Select
The ternary operator must have a condition, true value, and false value separated by '?' and ':'.
Step 2: Check each option for correct syntax and logic
var labels = numbers.Select(n => n > 0 ? "Positive" : "Non-positive").ToList(); correctly uses the ternary operator inside Select. Options B, C, and D have syntax errors or invalid expressions.
Final Answer:
var labels = numbers.Select(n => n > 0 ? "Positive" : "Non-positive").ToList(); -> Option A
Quick Check:
Correct ternary inside Select uses ? and : with both values [OK]
Hint: Use ? and : correctly inside lambda expressions [OK]
Common Mistakes:
Omitting colon ':' in ternary operator
Using if-else inside lambda without braces
Leaving false value empty
Recommended
Ready to prove it?
Pass the test and this pattern moves unknownstrongwhile earning +1 Grip toward your certificate.