How do I use the conditional (ternary) operator?

It works like this: (condition) ? true-clause : false-clause It’s most commonly used in assignment operations, although it has other uses as well. The ternary operator ? is a way of shortening an if-else clause, and is also called an immediate-if statement in other languages (IIf(condition,true-clause,false-clause) in VB, for example). For example: bool Three = … Read more

What does the question mark and the colon (?: ternary operator) mean in objective-c?

This is the C ternary operator (Objective-C is a superset of C): label.frame = (inPseudoEditMode) ? kLabelIndentedRect : kLabelRect; is semantically equivalent to if(inPseudoEditMode) { label.frame = kLabelIndentedRect; } else { label.frame = kLabelRect; } The ternary with no first element (e.g. variable ?: anotherVariable) means the same as (valOrVar != 0) ? valOrVar : … Read more

Nullable types and the ternary operator: why is `? 10 : null` forbidden? [duplicate]

The compiler first tries to evaluate the right-hand expression: GetBoolValue() ? 10 : null The 10 is an int literal (not int?) and null is, well, null. There’s no implicit conversion between those two hence the error message. If you change the right-hand expression to one of the following then it compiles because there is … Read more