Boxing and Unboxing
its a type and reference casting
Know the answer? Post it — somebody with the same question will find it here.
Sign in to answer this question
It is the same account you read, post and publish with — and you will come straight back to this page.
Dipen LamaPosted Jul 12, 2006, 7:32 AM
.NET defines two categories of data types - value type and reference type, while value type are stored in stack, reference type are stored in .Net managed heap, you may occasionally need to convert a variable of one type as a variable of the other type. .Net provides a very simple mechanism, boxing and unboxing
, to convert a value type to a reference type and vica-versa. Let us have variable of type int:int age = 30;
If, during the course of your application, you wish to represent this value type as a reference
type, you would “box” the value as follows:
object
objAge = age;Boxing can be formally defined as the process of explicitly converting a value type into a corresponding reference type by storing the variable in a
System.Object. When you box a value, the CLR allocates a new object on the heap and copies the value type’s value (in this case, 30) into that instance. What is returned to you is a reference to the newly allocated object. Using this technique, .NET developers have no need to make use of a set of wrapper classes used to temporarily treat stack data as heap-allocated objects.The opposite operation is also permitted through
unboxing. Unboxing is the process of converting the value held in the object reference back into a corresponding value type on the stack. The unboxing operation begins by verifying that the receiving data type is equivalent to the boxed type, and if so, it copies the value back into a local stack-based variable. For example, the following unboxing operation works successfully, given that the underlying type of the objAge is indeed a integer:int intAge = (int)objAge;