What is 'Un'-boxing?
A type-conversion method, (transformation, reversal), changing back from reference type to value type, after boxing (see elsewhere), has occurred. It impacts performance and processing time, thus resource intensive, should be minimized. With a value type, when it is ‘boxed’, it in actual fact, wraps the value inside a System.Object and stores it on the managed heap. Un-boxing then pertains to the process of extracting this value type from the object. It is useful for simple applications and assignments, but should not be overused. With boxing new objects are allocated and constructed. Casting for un-boxing then can impact performance. Un-boxing can be invalid and/or return an exception or unexpected error message.
Unboxing is an exact and explicit conversion from type object to a value type or from an interface type to a value type, that implements the interface. An unboxing operation, incident or event dynamic, consists of:
• Checking the object instance
• Ensuring it is a boxed value of the given value type
• Copying the value from the instance into the value-type variable
A good example of this application-in-action, would be tapping into the ThreadPool class provided by .Net. ThreadPool.QueueUserWorkItem() method allows queuing up a method for execution on a thread pool thread, where boxing and unboxing commands are the nuts-and-bolts to make it happen seamlessly.
Key Exam Points
- Use Un-boxing in many programming languages and environments, including C# and VB.
- Find exam study examples for Boxing and Un-boxing, that help you to gain a better understanding, real-life, applications and contexts
Boxing, Value Type, Reference Type
This article is based on the 2nd edition of the Microsoft .Net Framework Application Training Kit with the purpose to help 70-536 Exam takers to succeed. I constantly look for ways to improve the content. Please leave a comment about this article or drop me a message if you would like to see changes for this site.