Understanding Boxing and Unboxing in C#
Boxing and unboxing are the most important concepts you always get asked in your interviews. Actually, it's really easy to understand, and simply refers to the allocation of a value type (e.g. int, char, etc.) on the heap rather than the stack.
While working with the data types such as strings, objects, and arrays, we often need to convert the value types to the reference types or vice-versa. Because both have different characteristics and .NET stores them differently in the memory location, This must be required to do some work or defines some settings that work internally to convert them from one data type to another. These conversion processes are generally called as a terms boxing and unboxing.
Implicit conversion of a value type (int, char, etc.) to a reference type (object), is known as Boxing. In the boxing process, a value type is being allocated on the heap rather than the stack.
A boxing conversion is intended for creating a copy of the value being boxed. This type of conversion is completely different from a conversion of a reference type to a type object, in which the value that is being converted continues to reference the same instance and simply is regarded as the less derived type object.
Let's take a simple example of boxing that show how it happens while converting the data type as given below.
int abc = 10; object xyz = abc; // it performs the boxing
In the above example, the integer variable that is "abc" is assigned to the object "xyz". Thus the object data type is a reference type and base class of all the other classes in C# ultimately, an integer can be assigned to an object type. And this process of converting from the integer to the object data type is called boxing.
Explicit conversion of the same reference type (which is being created by the boxing process); back to a value type is known as unboxing. In the unboxing process, the boxed value type is unboxed from the heap and assigned to a value type that is being allocated on the stack.
In other words, The unboxing conversion is a completely reversed process of boxing that we have seen already. Unboxing is the process of converting a reference data type to a value type such as a string or integer. The unboxing conversion extracts the value from the reference type and assigns it to a value type.
// int (value type) is created on the Stack int stackVar = 12; // Boxing = int is created on the Heap (reference type) object boxedVar = stackVar; // Unboxing = boxed int is unboxed from the heap and assigned to an int stack variable int unBoxed = (int)boxedVar;
int i = 10; ArrayList arrlst = new ArrayList(); //ArrayList contains object type value //So, int i is being created on heap arrlst.Add(i); // Boxing occurs automatically int j = (int)arrlst; // Unboxing occurs
Sometimes boxing is necessary, but you should avoid it if possible since it will slow down the performance and increase memory requirements.
For example, when a value type is boxed, a new reference type is created and the value is copied from the value type to the newly created reference type. This process takes time and required extra memory (around twice the memory of the original value type).
Attempting to unbox a null cause a NullReferenceException.
int? stackVar = null; // Boxing= Integer is created on the Heap object boxedVar = stackVar; // NullReferenceException int unBoxed = (int)boxedVar; //Object reference not set to an instance of an object.
Attempting to unbox a reference to an incompatible value type causes an InvalidCastException.
int stackVar = 12; // Boxing= Integer is created on the Heap object boxedVar = stackVar; // InvalidCastException float unBoxed = (float)boxedVar; //Specified cast is not valid.
What do you think?
The boxing and unboxing type system unification provides the value types with the benefits of object characteristics without introducing the unnecessary overhead of the type conversions. For the developers, that don't need integer values to act as an object, integer values are simply 32 bit values ultimately. For developers that need integer values to behave like the objects, this capability of the types is available on demand. And the ability to treat the value types as objects bridges the gap between the value types and reference types that exists in most programming languages.
I hope you will enjoy the tips while programming with C#. I would like to have feedback from my blog readers. Your valuable feedback, question, or comments about this article are always welcome.
Take our free skill tests to evaluate your skill!
In less than 5 minutes, with our skill test, you can identify your knowledge gaps and strengths.