What is the ternary operator "?:" of the C# operator?
The ternary operator "?:" of the C# operator is sometimes called a conditional operator.
For the conditional expression b?x:y, first calculate the condition b and then make a judgment.
If the value of b is true, calculate the value of x and the calculation result is the value of x; otherwise, calculate the value of y and the calculation result is y.
A conditional expression never calculates x and y again. The conditional operator is associated to the right, that is, grouped from left to right.
The operation example of the three-part operator "?:" of the C# operator:
The expression a?b:c?d:e will be executed in the form of a?b:(C?d:e).
The second and third operands of ?: control the type of the conditional expression. Suppose x and y are the types of the second and third operands respectively, then:
●If x and y are the same type, then this type is the type of the conditional expression.
● Otherwise, if there is an implicit conversion from x to y, but there is no conversion from y to x, then y is the type of the conditional expression.
● Otherwise, if there is an implicit conversion from y to x, but there is no conversion from x to y, then x is the type of the conditional expression.
● Otherwise, no expression type is defined, and a compile-time error occurs
The basic content of the three-part operator "?:" of the C# operator is introduced to you here. I hope it will be helpful for you to understand and learn the three-part operator "?:" of the C# operator.
The ternary operator also becomes a conditional operator. It seems special because there are three operands, but it does belong to a type of operator.
Its form is
boolean-exp?value0 :value1
If the boolean-exp expression result is true, value0 is calculated, and this calculation result is the value finally generated by the operator. If the boolean-exp expression result is false, value1 is calculated, and the same way, its result will become the last value of the operator.
Of course it can also be replaced by if-else, but the ternary operator is completely different from if-else, and the operator will produce a value.
public class TernaryIfElse{
static int ternary(int i){
return i<10?i*100:i*10;
}
static int standardIfElse(int i){
if(i<10)
return i*100;
else
return i*10;
}
public static void main(String [] args){
(ternary(9));
(ternary(10));
standardIfElse( (9));
standardIfElse( (10));
}
}
Output
900
100
900
100
In comparison, ternary operators are much more compact, while if-else is easier to understand