?? Coalesce for empty string?

Something I find myself doing more and more is checking a string for empty (as in "" or null) and a conditional operator.

A current example:

s.SiteNumber.IsNullOrEmpty() ? "No Number" : s.SiteNumber;

This is just an extension method, it’s equivalent to:

string.IsNullOrEmpty(s.SiteNumber) ? "No Number" : s.SiteNumber;

Since it’s empty and not null, ?? won’t do the trick. A string.IsNullOrEmpty() version of ?? would be the perfect solution. I’m thinking there has to be a cleaner way of doing this (I hope!), but I’ve been at a loss to find it.

Does anyone know of a better way to do this, even if it’s only in .Net 4.0?

12 Answers
12

Leave a Comment