In my quest to become a C# expert I've decided that I should be able to accurately and unambiguously define each and every C# term and keyword. As such I'm going to try and create a post about each one in my own (and quoted) words to act as my own reference to this language.
Boxing and Unboxing
From the documentation: Boxing and unboxing enable value types to be treated as objects. Boxing a value type packages it inside an instance of the Object reference type. This allows the value type to be stored on the garbage collected heap. Unboxing extracts the value type from the object.
My understanding is that the Object class internally has a boolean HasValue property which if false means that this object has a "value" of null. If it's true then a value has been assigned. I also assume that there is a Type property which represents the type of object that has been stored (such as Int32) and also an area of memory for the object itself which represents the size of the object presumably obtained from the sizeof() operator.
Stuffing a value into an Object is called boxing and this is done by means of a cast:
Int32 i = 1;
Object o = (object) i;
Retrieving the value into a strongly typed type is called unboxing and this is also done using a cast:
i = (Int32) o;
- Boxing is expensive. Boxing an object happens on the heap and not the stack.
- Rob Paveza's blog entry Optimizing Memory Allocations - Pooling and Reusing Objects provides some excellent insights into optimization if you're doing a lot of boxing.