Boxing: Converting a value type to reference type is called boxing
int i = 101; object obj = (object)i; // Boxing
Boxing happens implicitly, where as unboxing is an explicit conversion.
Boxing is used to store value types in the garbage-collected heap. Boxing is an implicit conversion of a value type to the type object or to any interface type implemented by this value type. Boxing a value type allocates an object instance on the heap and copies the value into the new object.
Unboxing: Converting a reference type to a value typpe is called unboxing. An unboxing operation consists of:
- Checking the object instance to make sure that it is a boxed value of the given value type.
- Copying the value from the instance into the value-type variable.
obj = 101; i = (int)obj; // Unboxing
Attempting to unbox null causes a NullReferenceException. Attempting to unbox a reference to an incompatible value type causes an InvalidCastException.
Performance according to MSDN:
It is best to avoid using value types in situations where they must be boxed a high number of times, for example in non-generic collections classes such as ArrayList. You can avoid boxing of value types by using generic collections such as List. Boxing and unboxing are computationally expensive processes. When a value type is boxed, an entirely new object must be created. This can take up to 20 times longer than a simple reference assignment. When unboxing, the casting process can take four times as long as an assignment.
Comments Post a Comment
Arjunan 3/6/2013 (IST) / Reply
nice explanation.but you could have showed it with an arrayList example.