Comparison of zero and zero

Basically, a Nullable<T> is a structure that explains things like calling .HasValue will never throw a NullReferenceException . I was wondering why - given the NULL value, which does not matter - the comparison with null always true , even when using Object.ReferenceEquals , which I thought would return false, because it is a structure.

Is there any special behavior built into the CLR to make this possible? This probably also explains why the general structure constraint does not allow nullables.

Best wishes,
Oliver Hanappi

+4
source share
3 answers

If you do:

 int? x = null; if (x == null) 

which will use HasValue .

Using Object.ReferenceEquals the value will be entered first - and this will convert the null value to a null reference (which is really a special CLR behavior). When a null value type is placed in a box, the result is either a null reference or a field of a base value type. In other words, there is no such thing as a value in a box such as a NULL value.

+19
source

Incorrect comparisons do not always return true. Take this example, for example:

 int? n = null; int? m = 5; Console.WriteLine(n == null); // prints True Console.WriteLine(m == null); // prints False 

The CLR has special boxing behavior for Nullable s, so link comparisons work as you might expect. Essentially, the Value property of the structure is placed in the object cell.

+5
source

Yes, Nullable<T> is a special structure that uses compiler support. I wrote about what happens when it is compiled to IL here .

+2
source

All Articles