I’ve just started writing on a component where I found it might be useful to declare some of the properties nullable, instead of letting them resort to default values. However, I realized that I’ve never before used the non-nullable-type? syntax or the Nullable<T> type before, so there are probably some gotchas that’ll soon jump out and bite me. So…
-
What are the biggest gotchas when using
Nullable<T>and the shorthand?syntax? -
How do I work around them?
-
What are the biggest advantages/new possibilities that are made available to me when I start using them?
A common gotcha is attempting to assign to a nullable variable with a conditional expression as follows:
At first glance this might look like it should work but actually it gives a compile error:
Solution: add a cast to one or both of the possible outcomes:
Less commonly seen: Normally it is safe to assume that for integers
a <= 5and!(a > 5)are equivalent. This assumption is not true for nullable integers.Result:
Solution: Handle the null case separately.
Here’s another slight variation of the above:
Output:
So
yis equal toz, but it’s not less than or equal toz.Solution: Again, treating the null case separately can avoid surprises.