Alex Rivera | Logout

Is there any difference between myNullableLong.HasValue and myNullableLong != null?

Asked 2011-03-08T14:34:33.433
44

When I have a nullable long, for example, is there any difference between

myNullableLong.HasValue 

and

myNullableLong != null

... or is it just 'syntactic sugar'?

Edit
Report

1 Answer

8

It's syntactic sugar; Nullable<T> is actually a struct, so it cannot actually be null; the compiler turns calls that compare to null (like your second example) into calls to HasValue.

Note, though, that boxing a Nullable<T> into an object will result in either the value of T (if it has a value) or null (if it doesn't).

I.E.

int? foo = 10; // Nullable<int> with a value of 10 and HasValue = true
int? bar = null; // Nullable<int> with a value of 0 and HasValue = false

object fooObj = foo; // boxes the int 10
object barObj = bar; // boxes null

Console.WriteLine(fooObj.GetType()) // System.Int32
Console.WriteLine(barObj.GetType()) // NullReferenceException
answered 2011-03-08T14:36:10.827

Your Answer