Null-coalescing Operator

In my code there is lot of checks like this:

if (text == null) {
text = "Some default value";

With C# this line can be written as:

text = text ?? "Some default value";

This will definitely make code shorter and while I use strings here, it is not limited to them. Any object will do.

Most of time I find this syntax less readable than first example. Part is probably because I am not used to it and part is definitely because of those question marks (??). Somehow they make me uneasy.

However, it is great help in your database layer when you need to get some value out of nullable type:

int count = dbCount ?? 0;

Once you need to set ten fields to defaults if their value is null, you learn to appreciate it.

Leave a Reply

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