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;
Filed under: Software Development, Tip of the Day Tagged: C# 2, C# 3, C# 4, refactoring
