Monday 30 June 2008

The ternary prize

The ternary operator uses 2 symbols (? and :) to separate a conditional statement and 2 possible expressions. They can be used to represent a simple If...Else...End If statement on a single line:
condition ? expression1 : expression2

If the condition is true, expression 1 is evaluated. Alternatively, if the condition is false, expression 2 is evaluated.

Example:

Random random = new Random( DateTime.Now.Millisecond );

string response = random.Next( 1, 9 ) < 5 ? "the number is less than 5" : "the number is greater than or equal to 5";

No comments: