What Does Conditional Operator Mean?
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.
This term is also known as ternary operator or inline if (if).
Techopedia Explains Conditional Operator
A conditional operator is the only ternary operator (taking three operands) in C#. It forms as an alternative to the if-else construct, which provides better conciseness with less code and better readability. During compilation, the C# compiler translates the ternary expression into branch statements, which can condense multiple if statements and reduce nesting at the level of source code. Sometimes, the code generated for a ternary operator can boost performance by reordering some of the instructions.
Properties of a conditional operator are:
- It is right-associative, implying that operations are grouped form right to left.
- It always evaluates one of the two expressions specified after the conditional operator symbol. It never evaluates both.
- The first operand must be of integral or pointer type.
- The second and third operands must be convertible to one another and not mutually convertible to some other type.
- The type of result is the common type, which is an l-value, but only if both second and third operands are of the same type and both are l-values.
- Only assignment call, increment, decrement and new object expression can be used asa statement.
- When the result of an evaluation of an expression using ternary operator is used in a method return statement, its type should match the return type of the enclosing method for successful compilation.
- When the result is not a constant, the type of conditional expression is based on the more common one of the two types.