C# Ternary Operator
The ternary operator is a concise way to express a conditional statement.
It is often used as a shorthand for an if-else
statement when you need to assign a value to a variable based on a condition.
The basic syntax of the ternary operator is,
condition ? true_expression : false_expression;
int x = 10;
int y = 20;
int result = (x > y) ? x : y;
Console.WriteLine(result);
In this example, the condition (x > y)
is evaluated. If it is true, the value of x
is assigned to the variable result
; otherwise, the value of y
is assigned.
You can also use the ternary operator to perform different actions based on the condition.
int number = 7;
string resultMessage = (number % 2 == 0) ? "Even" : "Odd";
Console.WriteLine(resultMessage);
In this case, the condition (number % 2 == 0)
is checked, and if it is true, the string "Even" is assigned to resultMessage
; otherwise, "Odd" is assigned.
While the ternary operator can make code more concise, it's essential to use it judiciously to maintain code readability.
Complex expressions within the ternary operator can make code harder to understand, so it's often best suited for simple conditional assignments.