In C#, the concepts of boxing and unboxing hold immense significance as they provide a unified
There are three types in C# for a variable:
Value type: This deals with variables that hold values of int
, char
, float
, and so on.
Reference type: This deals with objects in C#.
Pointer type: This deals with the addresses of variables/objects.
Boxing deals with converting a value type to a reference type, while unboxing deals with converting a reference type to a value type.
Let's take an example for each concept and see how programmers use them to code efficiently.
We will implement the
using System;class HelloWorld{static void Main(){char valVariable = 'H';object refVariable;//boxingrefVariable = valVariable;valVariable = 'A';Console.WriteLine("Value of valVariable: {0}",valVariable);Console.WriteLine("Value of refVariable: {0}",refVariable);}}
Line 6: We declare and initialize the variable of a value type.
Lines 7–9: We declare the variable of the reference type with object
, and boxing occurs when it is initialized with the value type variable's value.
Lines 11–12: We print the output of both types to display how boxing changes the reference type variable's value to a value type. Even when we change the valVariable
's value, it does not reflect those changes in the refVariable
.
The code below shows the implementation of the concept of unboxing:
using System;class HelloWorld{static void Main(){int valVariable = 10;//boxingobject refVariable = valVariable;//unboxingint valVariable2 = (int)refVariable;Console.WriteLine("Value of refVariable:{0}",refVariable);Console.WriteLine("Value of valVariable2:{0}",valVariable2);}}
Line 6: We initialize the value type variable.
Line 8: We initialize the reference type variable with the value type variable's value.
Line 10: We initialize another value type variable with the reference type variable's value. Unboxing is the concept where (int)
represents this conversion.
Lines 11–12: We print the output of the refVariable
and the valVariable
to show how we can use unboxing to assign a reference type variable's value to a value type variable.
The following table represents the differences between the two concepts:
Boxing | Unboxing |
Conversion of value type to reference type. | Conversion of reference type to value type. |
Stack variable's value given to an object stored on heap. | Heap object's value given to a variable stored on the stack. |
Implicit conversion. | Explicit conversion. |
Free Resources