Tech moves fast! Stay ahead of the curve with Techopedia!
Join nearly 200,000 subscribers who receive actionable tech insights from Techopedia.
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 (iif).
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:
Join nearly 200,000 subscribers who receive actionable tech insights from Techopedia.