Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using nullable types in C#

Tags:

c#

nullable

I'm just interested in people's opinions. When using nullable types in C# what is the best practice way to test for null:

bool isNull = (i == null);

or

bool isNull = !i.HasValue;

Also when assigning to a non-null type is this:

long? i = 1;
long j = (long)i;

better than:

long? i = 1;
long j = i.Value;
like image 471
Martin Brown Avatar asked Nov 03 '08 18:11

Martin Brown


2 Answers

I would use this:

long? i = 1;
...some code...
long j = i ?? 0;

That means, if i is null, than 0 will be assigned.

like image 64
Seiti Avatar answered Oct 06 '22 21:10

Seiti


Use the forms that were specially implemented for you by the C# team. If anyone objects, tell them Anders said it was okay.

What I'm saying, flippantly, is that a lot of work went into integrating nullable types into c# to give you a good programming experience.

Note that in terms of performance, both forms compile down to the same IL, ie:

int? i = 1;
bool isINull = i == null;
int j = (int)i;

Ends up like this after the C# compiler has got to it:

int? i = 1;
bool isINull = !i.HasValue;
int j = i.Value;
like image 32
mackenir Avatar answered Oct 06 '22 22:10

mackenir