Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Boxing/Unboxing and Nullable?

Tags:

.net

nullable

I understand that boxing and unboxing is about casting (real type to object... object to real type). But I do not understand what the MSDN say about it with the Nullable. Here is the text I do not understand:

When a nullable type is boxed, the common language runtime automatically boxes the underlying value of the Nullable object, not the Nullable object itself. That is, if the HasValue property is true, the contents of the Value property is boxed. When the underlying value of a nullable type is unboxed, the common language runtime creates a new Nullable structure initialized to the underlying value. Source

When you change your object to a real type, the real type variable that was nullable will be the type of object? I do not get it?

like image 212
Rogez Sanchez Avatar asked Dec 17 '08 14:12

Rogez Sanchez


2 Answers

What it's saying is that if you do:

int? x = 5;
object y = x; // Boxing

You end up with a boxed int, not a boxed Nullable<int>. Similarly if you do:

int? x = null; // Same as new Nullable<int>() - HasValue = false;
object y = x; // Boxing

Then y ends up as a null reference.

like image 131
Jon Skeet Avatar answered Oct 31 '22 11:10

Jon Skeet


What that means is that if you do:

int? i = 5;
object o = i;

it is an "int" (5) that is boxed, not an "int?" (5). If x had been null (!HasValue), o would be null, not a box around an empty "int?"

Then when you unbox:

i = (int?)o;

If o is null, i becomes an empty "int?"; otherwise, the 5 is unboxed and used to create an "new int?(5)".

Basically, you shouldn't (short of cheating) be able to get a boxed nullable<T> directly - only a boxed T

like image 35
Marc Gravell Avatar answered Oct 31 '22 11:10

Marc Gravell