Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does a `null` Nullable<T> have a hash code?

Tags:

c#

nullable

Bit of a weird question...

But can anyone give me a justification for why this would be expected behaviour?

This just seems totally odd to me....

//Makes perfect sense object o = null; o.GetHashCode().Dump(); 

NullReferenceException: Object reference not set to an instance of an object.

//Seems very odd int? i = null; i.GetHashCode().Dump(); 

0

This obviously means:

int? zero = 0; int? argh = null;  zero.GetHashCode() == argh.GetHashCode(); //true 
like image 345
Dave Bish Avatar asked Feb 12 '18 13:02

Dave Bish


1 Answers

The point here is that

int? i = null; 

does not create a variable i which is null, but (by performing an implicit cast) a Nullable<int> instance which does not have a value.
This means the object/instance is not null (and as Nullable<T> is a struct/value type it actually can't be null) and therefore has to return a hash-code.

This is also documented here:

The hash code of the object returned by the Value property if the HasValue property is true, or zero if the HasValue property is false.

like image 113
Christoph Fink Avatar answered Sep 17 '22 20:09

Christoph Fink