Oliver Hanappi
Oliver Hanappi

Reputation: 12346

Comparing a nullable to null

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

Upvotes: 4

Views: 324

Answers (3)

Igor Zevaka
Igor Zevaka

Reputation: 76500

Yes, Nullable<T> is a special struct that enjoys compiler support. I have blogged about what happens when it gets compiled into IL here.

Upvotes: 2

LBushkin
LBushkin

Reputation: 131676

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

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 Nullables, such that reference comparison works as you might expect. Essentially, the Value property of the struct is boxed into an object.

Upvotes: 5

Jon Skeet
Jon Skeet

Reputation: 1500505

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.

Upvotes: 19

Related Questions