It's the conditional operator. (Sometimes incorrectly called the ternary operator; it's a ternary operator as it has three operands, but its name is the conditional operator. If another ternary operator is ever added to C#, "the ternary operator" will become an ambiguous/non-sensical phrase.)
Quick description:
The first operand is evaluated, and if the result is true
, the second operand is evaluated and forms the overall value of the expression. Otherwise the third operand is evaluated and forms the overall value of the expression.
There's a little more detail to it in terms of type conversions etc, but that's the basic gist.
Importantly, the first operand is always evaluated exactly once, and only one of the second or third operand is evaluated. So for example, this is always safe:
string text = GetValueOrNull();
int length = text == null ? 5 : text.Length;
That can never throw a NullReferenceException
as text.Length
isn't evaluated if text == null
is true.
It's also important that it's a single expression - that means you can use it in some places (such as variable initializers) where you couldn't use the if/else equivalent.
Closely related is the null-coalescing operator which is also worth knowing about.