The coalesce operator, BKA the double question marks
13 January, 2009 § 4 Comments
In C#, there is a nice little operator that is rarely used. I’m not sure if this is because most people haven’t heard of it before or they just don’t know how to use it.
Basically, this operator allows you to check if an object is null, and if it is, return a different object.
return userName ?? string.Empty;
Instead of this:
return (userName != null) ? userName : string.Empty;
Pretty simple, and it will save some typing. I’ve heard arguments against using the ternary operator from people claiming not to use it because fellow developers wouldn’t know what it is. That’s not the mindset we should have. If an operator exists in a language and there is a perfectly valid use for it, then go ahead and use it. When your colleage sees it, they will learn something about the language they never knew before and will most likely appreciate it.