How can the CLR get around a throw error when nulling a structure?

I am trying to understand one thing in this code:

Nullable<Int32> x = 5;
Nullable<Int32> y = null;
Console.WriteLine("x: HasValue={0}, Value={1}",  x.HasValue, x.Value);
Console.WriteLine("y: HasValue={0}, Value={1}",  y.HasValue, y.GetValueOrDefault());

And Conclusion:

x: HasValue=True, Value=5
y: HasValue=False, Value=0

And what I do not understand when you go nullto y, I believe that it calls public static implicit operator Nullable<T>(T value), but the definition of this method initializes a new transfer of the structure value, which is assigned nullhowever the constructor method does not check whether it is null or not, so it can assign default(T) value.

Why can we even assign null to a struct here and it works fine?

Can you guys what I'm missing here? I don’t understand how he just walked around nulland returned the default value.

Internal definition of Nullable code:

http://codepaste.net/gtce6d

+5
source
4

, Nullable ( T)

, , T Int32 , null Int32. y , , 0. HasValue, false.

null , # .

+6

, new Nullable<T>(value); ( 40)

+1

, null NULL . hasValue false.

+1

A Nullable<T> - , , , , , ( ) , . - null, Nullable<T> . Nullable<T> to null " " ( HasValue) false " " ( Value) .

Personally, I think that pretending Nullable<T>which HasValueis false, nullmore confusing than helpful, but I do not Microsoft. I would have thought Nullable<T>it would be more beneficial for each type to have a static property Nullable<T>.Null(which would be equivalent default(Nullable<T>), but the behavior is Nullable<T>reasonably well founded. I doubt that it will ever change.

+1
source

All Articles