C# Conditional (Ternary) Operator
The conditional (ternary) operator in C# is a shorthand for the if-else
statement. It evaluates a condition and returns one of two expressions based on whether the condition is true or false.
Key Topics
Syntax
The syntax for the conditional (ternary) operator is:
condition ? trueExpression : falseExpression;
Example: Conditional (Ternary) Operator
int a = 5;
int b = 10;
string result = (a > b) ? "a is greater" : "b is greater";
Console.WriteLine(result);
Output:
b is greater
Code Explanation: The ternary operator checks if a
is greater than b
. Since it is not, the expression returns "b is greater"
.
Key Takeaways
- The conditional (ternary) operator is written as
condition ? trueExpression : falseExpression
. - It can be used as a shorthand for simple
if-else
statements.