Basically, Nullable<T> is a structure, which explains things like calling .HasValue will never throw a NullReferenceException. I was wondering why – given a nullable which does not have a value – comparisons to null are always true, even when using Object.ReferenceEquals, which I thought would return false because it is a structure.
Is there special behaviour built into the CLR to make this possible? It would probably also explain why the generic struct constraint does not allow nullables.
Best Regards,
Oliver Hanappi
If you do:
that will use
HasValue.Using
Object.ReferenceEqualswill box the value first – and that will convert the null value into a null reference (which is indeed special CLR behaviour). When a nullable value type is boxed, the result is either a null reference or a box of the underlying value type. In other words, there’s no such thing as a boxed value of a nullable value type.