One of the features of C# 2.0 is the null coalescing operator (??) which says that if the value is not null, then use it otherwise use another value.
For example, if we wanted to use the myCust variable if it wasn’t null, or if it was use order.Cust then we would write.
Customer c = myCust ?? order.Cust;
Using 1.1, we would use the ternary operator (?) and it would have been
Customer c = if(myCust != null) ? myCust : order.Cust
We could have chained this together, so we could also check order.Cust to see if that was null and provide an alternative to that.
However, one problem I had was with String.Empty. I wanted to test to see if a string was returned from a method and if it wasn’t, use the system default.
String importantStr = myObject.GetImportantString() ?? sysDefault;
The problem is that myObject.GetImportantString() returns string.empty if it cannot be found. The operator doesn’t treat string.empty as a null and uses it as the variable value. Not what I wanted at all!
Sadly, I had to go back and use the ternary operator.
String importantStr = if(!string.IsNullOrEmpty(myObject.GetImportantString()) ? myObject.GetImportantString() : sysDefault;
Sadly, myObject.GetImportantString() is an expensive call so calling it twice is bad. So I had to resort to the old way of doing things
string temp = myObject.GetImportantString();
string importantStr = sysDefault;
importantStr = temp;
Oh well, still a useful operator. Just not for strings…