24. January 2007 00:43
Not sure how I missed this during my C# 2.0 reading, or during my hundreds of hours of C# 2.0 coding, but there is a nifty new operator available.
The ?? operator is essentially a shortcut for checking to see if a value is null, and if so, returning a different value. It's very similar to the SQL statement IsNull.
The syntax for this nifty operator is as follows:
string myString = (someVariable ?? "it was null");
So, in this case, if someVariable was null the variable myString would get the value of "it was null", otherwise it would get the value of someVariable. This could also be expressed with the slightly longer:
string myString = (someVariable != null ? someVariable : "it was null");
And that, of course, is a shorter version of the much longer:
if(someVariable == null)
myString = "it was null";
myString = someVariable;
I like it! I have absolutely no idea how I missed this. I love this kind of stuff.