C# Null Coalescing Operator (??) and String.Empty

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;
if(!string.IsNullOrEmpty(importantStr))
   importantStr = temp;

Oh well, still a useful operator.  Just not for strings…

Technorati Tags:

3 thoughts on “C# Null Coalescing Operator (??) and String.Empty”

  1. String.Empty is a perfectly valid string, and is not null. myObject.GetImportantString() should return null, not string.Empty, if a string cannot be found. This is how all collections work.

Leave a Reply

Your email address will not be published. Required fields are marked *