Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
215 views
in Technique[技术] by (71.8m points)

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

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
question from:https://stackoverflow.com/questions/48748209/why-does-a-null-nullablet-have-a-hash-code

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...