Conditional Operators

The conditional operator is the only ternary operator in the C# language, meaning it has three operands. Some people like to refer to it as the ternary operator. I dislike this particular wording because nothing prevents the language designers from adding another ternary operator at some point. So, the conditional operator it is.

Being an expression, the conditional operator produces a value from its operands. In essence, it’s a decision operator that computes and produces either the second or third operand’s value, based on the outcome of the first operand’s truth value. An example will make this clear:

int absOfX = x >= 0 ? x : -x;

In the preceding example, first the Boolean-valued relational expression x > 0 gets evaluated. ...

Get C# 5.0 Unleashed now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.