C# involves the Ternary operator
?:, a unique kind of decision-making operator.
Boolean Expression ? First Statement : Second Statement
As shown in the syntax above, there are three components to the Ternary operator.
First portion (before?) involves a boolean value returned by conditional expression True or False.
The second part (after and before:) contains a statement to be returned if the conditional expression evaluates to be true in the first part.
The third part contains another declaration that will be returned if the term returns false.
Note: The ternary operator returns the second or third portion of the value or expression. The statements will not be executed.
Take the following instance where x > y returns true and so the first statement after? executes.
int x = 50, y = 30; var result = x > y ? "x is greater than y" : "x is less than or equal to y"; Console.WriteLine(result);
Any data type can be returned by a ternary operator. It is therefore recommended to save it in var, which is implicitly typed.
For instance, as shown below, it can return an integer value.
int x = 30, y = 50; var result = x > y ? x : y; Console.WriteLine(result);
Instead of if-else declaration, ternary operator can also be used. If-else statements can be used to write the above example as shown below.
int x = 20, y = 10; int result = 0; if (x > y) result = x; else if (x < y) result = y; Console.WriteLine(result);
Nesting ternary operators are feasible, as a second (after?) or third part (after:) the ternary operator, by including conditional expression. Take the instance below.
int x = 2, y = 10; string result = x > y ? "x is greater than y" : x < y ? "x is less than y" : x == y ? "x is equal to y" : "No result";
The ternary operator is right-associative menas It will be evaluted from right to left. The expression
a ? b : c ? d : e is evaluated as
a ? b : (c ? d : e), not as
(a ? b : c) ? d : e.