views:

105

answers:

1
+7  A: 

(This is a duplicate, but it's hard to search for, so I'm happy enough to provide more another target for future searches...)

It's the null-coalescing operator. Essentially it evaluates the first operand, and if the result is null (either a null reference or the null value for a nullable value type) then it evaluates the second operand. The result is whichever operand was evaluated last, effectively.

Note that due to its associativity, you can write:

int? x = E1 ?? E2 ?? E3 ?? E4;

if E1, E2, E3 and E4 are all expressions of type int? - it will start with E1 and progress until it finds a non-null value.

The first operand has to be a nullable type, but e second operand can be non-nullable, in which case the overall expression type is non-nullable. For example, suppose E4 is an expression of type int (but all the rest are still int? then you can make x non-nullable:

int x = E1 ?? E2 ?? E3 ?? E4;
Jon Skeet
really useful to know - does it work in most programming languages?
Thomas Clayson
@Thomas: Nope, only C# as far as I'm aware. VB may have something similar, and some other languages have null-safe deferencing.
Jon Skeet
@Thomas Clayson: A null-coalescing operator basically exists in [C# and Perl](http://en.wikipedia.org/wiki/Null_coalescing_operator) as of version 5.10 (Perl syntax is `//`).
0xA3
Many thanks for this answer, very handy to know! Any idea if such a thing exists in VB.NET?
m.edmondson
oh rubbish :p (and 15 chars)
Thomas Clayson
@0xA3: Thanks for the correction. I hadn't come across that.
Jon Skeet