C# Ternary Operator


The ternary operator in C# is a shorthand way to write an if-else statement in a single line of code. It has the following syntax:

condition ? expression1 : expression2

Here, condition is a boolean expression that evaluates to true or false. If condition is true, the operator evaluates expression1; otherwise, it evaluates expression2.

For example, the following code uses the ternary operator to assign the value of x based on whether y is greater than 10:

int x;
int y = 15;

x = (y > 10) ? 5 : 10;

In this code, y > 10 is the condition. If it is true, the operator evaluates to 5; otherwise, it evaluates to 10.

It's important to note that the ternary operator should be used sparingly and only for simple expressions. Using it for more complex expressions can make the code difficult to read and understand. In general, it's better to use an if-else statement for more complex logic.

Also, be careful not to use the ternary operator for side effects (i.e., changing the state of variables or objects) since it can make the code less readable and harder to debug. The ternary operator should be used only for simple expressions that don't have side effects.