The ?? operator (C# 2.0)
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 a null coalescing operator. Here’s a conditional expression, in three different forms, but with the same meaning:
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:






Nice.
Comment by Marcus Mac Innes — 15/6/2005 @ 12:56 pm - 3 years, 2 months ago
very usefull operator … thanks for the tips
Comment by Mihir Solanki — 17/6/2005 @ 11:12 am - 3 years, 2 months ago
It could have been a good thing if the ?? operator worked with dbnull values returned from a database. These values are ussually checked prior to assigning to some variable
For example
If only i could do this
BookID = (int?)dRow["bookid"] ?? null;
instead of this
if (dRow["bookid"] != DBNull.Value)
{ BookID = (int?)dRow["bookid"]; }
else
{ BookID = null; }
I ‘ll put it on my next wishlist
Comment by Vin K — 14/8/2007 @ 7:46 am - 1 year ago
Vin K, that code can be written as the following :
BookId = dRow["BookId"] as int?;
Comment by Anon — 7/4/2008 @ 11:03 am - 5 months ago