The Null-Coalescing Operator In C#

One bad habit that can occur when using a different programming language than the one you are used to, is writing code that looks very similar to the old language you are used to.

I found myself in this trap earlier, and only spotted it during a code review.

I had been using the ternary operator to compare and return results something like this in C#.

string currentStation = (selectedStation != null ? currentStation : "Q Radio");

It works, but C# provides something far nicer called the null-coalescing operator, ??, which lets you set a default value when you try to assign a nullable type to a non-nullable type.

The example above could be rewritten like this…

string currentStation = selectedStation ?? "Q Radio";

You can read more about the ?? operator for C# on the MSDN website.