A while ago, I read a tiny note about this in somebody’s blog and I want to start off by apologizing to that somebody because for the life of me I can’t figure out who it might have been – so no reference here. Sorry about that. Anyway, I followed up on the original information and I thought it couldn’t hurt to pull peoples’ attention to this a bit more. So, the
?? operator: It’s an extension in C# 2.0 (find the specs here, this operator is explained on page 14, then end of chapter 19.5) and they call it the null coalescing operator. Here’s a conditional expression, in three different forms, but with the same meaning:
MyClass anObject; ... // Variant 1: Using a full if/else clause MyClass anotherObject; if (anObject != null) anotherObject = anObject; else anotherObject = new MyClass(); // Variant 2: Using the ?/: conditional operator MyClass anotherObject = anObject != null ? anObject : new MyClass(); // Variant 3: Using the ?? operator MyClass anotherObject = anObject ?? new MyClass();
So this should really make the purpose of the operator quite clear: check something for null, return the same something if it’s not null, the given alternative value otherwise. This functionality is slightly extended where it comes to nullable types. Normally, if both parameters to the
?? operator are nullable types, the return type will be the same nullable type. This doesn’t differ from the behaviour with any other type. But if only the first parameter is a nullable type while the alternative value is not nullable, the result type will be the non-nullable “base” type and the Value property of the nullable will be evaluated if necessary. So this is all valid code:
int? foo = null; int bar = foo ?? 42; // bar is now 42 foo = 52; bar = foo ?? 42; // bar is now 52 because foo.Value has been evaluated int? nbar = foo ?? 42; // nbar is now 52, but it's also a nullable type because the int has // been converted back to an int? immediately
Sorry, this blog does not support comments. Why not?
I used various blog hosting services since this blog was established in 2005, but unfortunately they turned out to be unreliable in the long term and comment threads were lost in unavoidable transitions. At this time I don't want to enable third-party services for comments since it has become obvious in recent years that these providers invariably monetize information about their visitors and users.
Please use the links in the page footer to get in touch with me. I'm available for conversations on Keybase, Matrix, Mastodon or Twitter, as well as via email.