Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What makes Nullable type can be assigned a null?

Tags:

c#

.net

We know that we can assign null to a nullable type. For example:

Nullable<Int32> x = 2021;
Nullable<Int32> y = null;

We know the second statement works because we were told it works, and we just take it and don't ask why. But if you look at the source code of Nullable<T> is:

public struct Nullable<T> where T : struct {
   ...
   public static implicit operator Nullable<T>(T value) {
      return new Nullable<T>(value);
   }
   public static explicit operator T(Nullable<T> value) {
      return value.Value; 
   }
}

The reason we can assign an int to Nullable<Int32> as Nullable<Int32> x = 2021; is because of the implicit operator, which allow you implicit cast an int to Nullable<Int32>. According to the rule of the implicit operator, T as the right hand side of =, has to be a struct type, but null is clearly not a legal struct value, so how can we do Nullable<Int32> y = null;(not to mention Nullable<Int32> itself is a struct) and why it doesn't violate the implicit operator rule


1 Answers

Checking for null and assigning null to a variable of type Nullable<T> is explicitly covered by the compiler.

So

int? i = ...
if (i == null) ...

is converted to

if (!i.HasValue)

and

i = null;

is converted to

i = default(Nullable<int>);

And a default(Nullable<int>) assigns an "empty" (zero-initialized) Nullable<int>. Hence its HasValue property is false, which is the semantic equivalent of a int? being null.

like image 148
René Vogt Avatar answered Feb 18 '26 12:02

René Vogt



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!