Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Comparing a nullable to null

Tags:

c#

nullable

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

like image 648
Oliver Hanappi Avatar asked Nov 27 '22 23:11

Oliver Hanappi


1 Answers

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.

like image 155
Jon Skeet Avatar answered Dec 10 '22 06:12

Jon Skeet