C# Conditional Operator
The twelfth part of the C# Fundamentals tutorial examines the conditional operator. This interesting ternary operator permits one of two values to be selected based upon a Boolean condition.
So far in the C# Fundamentals tutorial we have considered a number of unary operators that accept a single operand. We have also examined many binary operators that require two operands to function. The C# conditional operator is a ternary operator in that it has three operands.
The Conditional Operator
The conditional operator allows you to define a condition that returns a Boolean value. In addition to the condition, two expressions are provided. Only one of these expressions will be evaluated when the program is running, being selected according to the result of the condition. This allows you to craft a simple if-then-else statement.
The conditional operator uses the question mark and colon symbols (? and :) to separate the condition and the possible expressions to give the following syntax:
condition ? true-expression : false-expression
The condition part of the statement above can be any expression that returns a Boolean result. This can range from a simple Boolean variable to a complex expression using a mixture of Boolean and relational operators. Once evaluated, if the condition returns true then the returned result of the entire statement will be that of true-expression. If the condition returns false the statement evaluates to false-expression.
The conditional operator is widely used in C# and it is important that it is understood correctly. This section provides code samples that use the operator.
Example 1 - Validation
// Ensure that the user-provided value is at least the minimum permitted
int valueToUse = userEntered >= minimumValue ? userEntered : minimumValue;
The first example shows the conditional operator ensuring that a value entered by the user falls within a valid range. The condition checks that the value entered by the user is greater than or equal to the minimum permitted value. If it is then the user's value is assigned to valueToUse. If not, the minimum value is used instead.
Example 2 - Obtaining the Absolute Value
// Return the absolute value
int absoluteValue = value >= 0 ? value : -value;
The second example provides a simple absolute function. This function simply checks if the value provided is positive or negative. Negative values are then adjusted to be positive. NB: There is a true absolute function that you should use instead of this sample code.
We can now extend the operator precedence table with the conditional operator.
|Increment / Decrement Operators|
|++(postfix) --(postfix) ++(prefix) --(prefix)|
|Basic Arithmetic Operators|
|* / % + -|
|Bitwise Shift Operators|
|< > <= >=|
|Logic / Bitwise Operators|
|& ^ | && |||
|Compound Assignment Operators|
|*= /= %= += -= >>= <<= &= ^= |=|
24 September 2006