Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Gotchas when making use of Nullable<T> in C# 4

Tags:

c#

nullable

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?

like image 308
Tomas Aschan Avatar asked Jul 19 '10 22:07

Tomas Aschan


2 Answers

A common gotcha is attempting to assign to a nullable variable with a conditional expression as follows:

bool useDefault = true;
int defaultValue = 50;
int? y = useDefault ? defaultValue : null; 

At first glance this might look like it should work but actually it gives a compile error:

Type of conditional expression cannot be determined because there is no
implicit conversion between 'int' and '<null>'

Solution: add a cast to one or both of the possible outcomes:

int? y = useDefault ? defaultValue : (int?)null; 

Less commonly seen: Normally it is safe to assume that for integers a <= 5 and !(a > 5) are equivalent. This assumption is not true for nullable integers.

int? x = null;
Console.WriteLine(x <= 5);
Console.WriteLine(!(x > 5));

Result:

False
True

Solution: Handle the null case separately.


Here's another slight variation of the above:

int? y = null;
int? z = null;
Console.WriteLine(y == z);
Console.WriteLine(y <= z);

Output:

True
False

So y is equal to z, but it's not less than or equal to z.

Solution: Again, treating the null case separately can avoid surprises.

like image 127
Mark Byers Avatar answered Nov 01 '22 02:11

Mark Byers


Something people are often surprised by is that there is no such thing as a boxed nullable value type. If you say:

int? x = 123;
int? y = null;
int z = 456;
object xx = x;
object yy = y;
object zz = z;

you might think that since zz contains a boxed int, that xx and yy contain boxed nullable ints. They do not. xx contains a boxed int. yy is set to null.

like image 29
Eric Lippert Avatar answered Nov 01 '22 02:11

Eric Lippert