Tip of the day: Using the null-coalescing operator over the conditional operator

I’ve recently been refactoring a lot of code that used the conditional operator and looked something like this:

int someValue = myEntity.SomeNullableValue.HasValue
                    ? myEntity.SomeNullableValue.Value
                    : 0;

That might seem less verbose than the traditional alternative, which looks like this:

int someValue = 0;
if (myEntity.SomeNullableValue.HasValue)
    someValue = myEntity.SomeNullableValue.Value;

…or other variations on that theme.

However, there is a better way of expressing this. That is to use the null-coalescing operator.

Essentially, what is says is that the value on the left of the operator will be used, unless it is null in which case the value ont the right is used. You can also chain them together which effectively returns the first non-null value.

So now the code above looks a lot more manageable and understandable:

int someValue = myEntity.SomeNullableValue ?? 0;


  1. Marc Gravell says:

    It is interesting (maybe) to note that this also avoids a double-check on `.HasValue` that you normally get (one in `.Value`) – since the compiler emits:

    int someValue = (the nullable).HasValue ? (the nullable).GetValueOrDefault() : 0;

    however, it is a bit odd that it doesn’t choose:

    int someValue = (the nullable).GetValueOrDefault(0);

    or even more terse in this case with 0, you can avoid even the single check:

    int someValue = (the nummable).GetValueOrDefault();

    No real point to make here, other than an interesting API choice inside the compiler.

  2. Marc Gravell says:

    lol at the typo; “nummable”… Freudian?

Leave a Comment

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s