Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How CLR can bypass throwing error when assigning a null value to the struct?

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 Output is:

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

And the thing that I don't understand when you pass null to y, I believe it calls public static implicit operator Nullable<T>(T value) but the definition of this method initializes a new struct passing value which is assigned null however constructor method doesn't check whether it is null or not so it can assign default(T) to value.

How come we can even assign null to struct here and it works fine?

Can you guys what I am missing out here? I don't understand how it just bypassed null and returned default value.

Nullable code inner definition:

http://codepaste.net/gtce6d

like image 874
Tarik Avatar asked Jun 03 '12 00:06

Tarik


3 Answers

believe it calls public static implicit operator Nullable(T value)

No it doesn't, because T is Int32 in this case, and null is not an Int32. It just leaves the y variable default, which means for a struct that all bytes are 0. This results in a struct that has a HasValue that returns false.

You can't really pass null to a struct, but the C# compiler is converting this for you to a default initalization.

like image 105
Steven Avatar answered Nov 14 '22 22:11

Steven


The default is assigned in the constructor called by new Nullable<T>(value); (Line 40)

like image 45
Eugen Rieck Avatar answered Nov 15 '22 00:11

Eugen Rieck


My guess is that assigning null to a nullable calls the default constructor. That is the only possible way for hasValue to remain false.

like image 29
Dave Cousineau Avatar answered Nov 14 '22 23:11

Dave Cousineau