VIII-Conditional Operator " ? : "
A conditional operator in C#, is an operator that takes three operands (conditions to be checked), the value when the condition is true and value when the condition is false.
A conditional operator is represented by the symbol '?:'. The first operand (specified before the '?:') is the evaluating (conditional) expression. It has to be such that the type of evaluated expression can be implicitly converted to 'bool' or that implements operator true in order to avoid compilation errors. The second and third operands control the type of conditional expression. It is more often used in assignment and not as a statement producing compilation errors.
If the return value of the first operand (conditional expression) is true, the second operand is evaluated. Otherwise, the third operand is evaluated. Hence, the result of the conditional operator is the result of evaluation of the expression considered for evaluation.
For an expression stated as x?a:b, operand a will be evaluated if only the operand x (the conditional expression) returns true. Otherwise, operand b will be evaluated.
0 Comments