Boxing and Unboxing in C#
C# has two types of data types, One is value types and others are reference types. Value type stores the data itself, whereas the reference type stores the address of the data where it is stored. Value type is stored on the stack while Reference type is stored on the heap. Some predefined data types such as int, float, double, decimal, bool, char, etc. are value types and object, string, and array are reference types.
While working with these data types, we often need to convert value types to reference types or vice-versa. These conversion processes are called boxing and unboxing.
Boxing
Boxing is the process of Converting a Value Type (char, int etc.) to a Reference Type(object). Boxing is implicit conversion process in which object type (supertype)
is used.
Example :
int num1 = 20; Object Obj1 = num1;
Description: First declare a value type variable (num1) of type integer and assigned it with value 20. Now create a references object type (obj1) and applied Explicit
the operation which results in num1 value type to be copied and stored in object reference type obj1.
Boxing
Let’s understand with a more practical example :
// C# code for Boxing using System; class Test { static public void Main() { int num1 = 2020; // boxing object obj1 = num1; num1 = 100; System.Console.WriteLine("Value - type value of num1 is : {0}", num1); System.Console.WriteLine("Object - type value of obj1 is : {0}", obj); } }
Output:
Value - type value of num1 is : 100 Object - type value of obj1 is: 2020
Unboxing
Unboxing is the process of converting reference type to a value type. It is an explicit conversion process.
Example : int num1 = 20; Object Obj1 = num1; // Boxing int i = (int)Obj1; // Unboxing
Description: First declare a value type variable (num1) of type integer and assigned it with value 20. Now, create a reference object type (obj1). The explicit operation for boxing create a value type integer I and applied casting method.
Let’s understand with a more practical example:
// C# code for Unboxing using System; class Test { // Main Method static public void Main() { int num1 = 20; // boxing object obj1 = num1; // unboxing int i = (int)obj1; // Display result Console.WriteLine("Value of object obj1 is : " + obj1); Console.WriteLine("Value of i is : " + i); } }
Output:
Value of ob object is: 23 Value of i is: 23
Note: Boxing and unboxing degrade the performance. So, avoid using it. Use generics to avoid boxing and unboxing. For example, use List instead of ArrayList.