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:
int? x = null;
if (x == null)
that will use HasValue
.
Using Object.ReferenceEquals
will 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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With