The Ternary Operator

The simplest way to perform a comparison is to use the ternary (or conditional ) operator mentioned in the previous tutorials. You ’ ve already seen unary operators that work on one operand, and binary operators that work on two operands, so it won ’ t come as a surprise that this operator works on three operands. The syntax is as follows:

< test > ? < resultIfTrue > : < resultIfFalse >

Here, < test > is evaluated to obtain a Boolean value, and the result of the operator is either < resultIfTrue > or < resultIfFalse > based on this value.You might use this as follows:

string resultString = (myInteger < 10) ? "Less than 10": "Greater than or equal to 10";

The result of the ternary operator is one of two strings, both of which may be assigned to resultString . The choice of which string to assign is made by comparing the value of myInteger to 10, where a value of less than 10 results in the first string being assigned, and a value of greater than or equal to 10 results in the second string being assigned. For example, if myInteger is 4 , then resultString will be assigned the string Less than 10 .


You may also like...