Well, it's not quite the same as the conditional operator, but I think you're thinking of the null coalescing operator (??). (I guess you did say it was "similar" :) Note that "ternary" just refers to the number of operands the operator is - so while the conditional operator is a ternary operator, the null coalescing operator is a binary operator.
It broadly takes this form:
result = first ?? second;
Here second
will only be evaluated if first
is null. It doesn't have to be the target of an assignment - you could use it to evaluate a method argument, for example.
Note that the first operand has to be nullable - but the second doesn't. Although there are some specific details around conversions, in the simple case the type of the overall expression is the type of the second operand. Due to associativity, you can stack uses of the operator neatly too:
int? x = GetValueForX();
int? y = GetValueForY();
int z = GetValueForZ();
int result = x ?? y ?? z;
Note how x
and y
are nullable, but z
and result
aren't. Of course, z
could be nullable, but then result
would have to be nullable too.
Basically the operands will be evaluated in the order they appear in the code, with evaluation stopping when it finds a non-null value.
Oh, and although the above is shown in terms of value types, it works with reference types too (which are always nullable).