Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does Nullable<T> HasValue property not throw NullReferenceException on Nulls?

Tags:

Consider the following code:

DateTime? ndate = null; Console.WriteLine(ndate.HasValue); 

I would have expected a NullReferenceException, but HasValue will indeed return false. However, since ndate is null, how does the property invocation succeed, since there is no object to invoke the property HasValue on?

like image 372
Nathan Avatar asked Feb 03 '10 18:02

Nathan


1 Answers

Technically, "ndate" is not null - it is a value type, with it's value specified as being null.

When you write DateTime?, this is just shorthand for Nullable<DateTime>, which is a struct. There is no way for this to technically be null, since it's not a reference type.

like image 84
Reed Copsey Avatar answered Oct 20 '22 01:10

Reed Copsey