C# Ternary Operator
The ternary operator in C#, represented by ?:
, is a concise way to perform conditional evaluations and return values based on a condition. It acts as a simplified if-else
statement that returns a value.
Key Topics
1. Syntax of Ternary Operator
condition ? expression_if_true : expression_if_false;
If the condition
is true
, the operator returns expression_if_true
; otherwise, it returns expression_if_false
.
2. Basic Ternary Operator Example
Example: Simplifying an if-else Statement
int number = 10;
string result = (number % 2 == 0) ? "Even" : "Odd";
Console.WriteLine($"The number is {result}."); // Outputs: The number is Even.
Output:
The number is Even.
3. Nested Ternary Operators
Ternary operators can be nested to handle multiple conditions, but this can reduce code readability.
Example: Grading with Ternary Operator
int score = 85;
string grade = (score >= 90) ? "A" :
(score >= 80) ? "B" :
(score >= 70) ? "C" : "F";
Console.WriteLine($"Grade: {grade}"); // Outputs: Grade: B
Explanation: While nested ternary operators can be used, they can make the code harder to read. In such cases, an if-else
or switch
statement might be clearer.
4. Ternary Operator vs if-else Statement
The ternary operator is useful for simple conditional assignments, but for more complex logic, an if-else
statement is preferable.
Example: Comparing Ternary and if-else
// Using if-else
string status;
if (isActive)
{
status = "Active";
}
else
{
status = "Inactive";
}
// Using ternary operator
string status = isActive ? "Active" : "Inactive";
5. Best Practices for Using Ternary Operator
- Use the ternary operator for simple, concise conditional assignments.
- Avoid nesting ternary operators to prevent confusing code.
- Ensure that both expressions return compatible types.
- Prefer readability over brevity; if the ternary operator makes the code hard to read, use an
if-else
statement instead.
Key Takeaways
- The ternary operator provides a shorthand for simple conditional evaluations.
- It returns a value based on a boolean condition.
- Overuse or nesting of the ternary operator can reduce code readability.
- Choose between the ternary operator and
if-else
based on code clarity and complexity.