The ternary operator ?:
A Boolean operator capable of being executed inline.
The result type of the ternary operator is defined by the output expressions after the ? and : tokens.
LH = <boolean expression> ? <output 1> : <output 2>
The type of LH must be compatible with both <output 1> and <output 2>
Example | Result |
---|---|
int index = 2;
int result = 10 > index ? 5 : 7;
Console.WriteLine($"result is {result}"); | result is 5 Notice result type is int |
int index = 2;
int result = index > 10 ? 5 : 7;
Console.WriteLine($"result is {result}"); | result is 7 Notice result type is int |
int index = 2;
int result = 10 > index ? 5 : '7';
Console.WriteLine($"result is {result}"); | result is 5 Notice result type is int |
result is 55 - 55 is the ASCII decimal encoding for character '7' Notice result type is int | |
result is '7' - the character 7 Notice the casting the integer 5 to a char. This is necessary to avoid compilation errors in regards to type compatibility. | |
result is 55 - 55 is the ASCII decimal encoding for character '7' Notice the expression is wrapped in parenthesis |
FAQ: How do I choose between using an if-else statement and using an inline ternary operator?
Consider which one appears to be the most readable, and most clearly expresses the intent of the code