Boxing and unboxing are important concepts in C#. The C# Type System contains three data types: Value Types (int, char, etc), Reference Types (object) and Pointer Types. Basically, Boxing converts a Value Type variable into a Reference Type variable, and Unboxing achieves the vice-versa. Boxing and Unboxing enable a unified view of the type system in which a value of any type can be treated as an object.
Boxing In C#
- The process of converting a Value Type variable (char, int etc.) to a Reference Type variable (object) is called Boxing.
- Boxing is an implicit conversion process in which object type (super type) is used.
- Value Type variables are always stored in Stack memory, while Reference Type variables are stored in Heap memory.
- Example :
int num = 23; // 23 will assigned to num
Object Obj = num; // Boxing
- Description : First, we declare a Value Type variable num of the type int and initialise it with value 23. Now, we create a Reference Type variable obj of the type Object and assign num to it. This assignment implicitly results in the Value Type variable num to be copied and stored in Reference Type variable obj as shown in below figure :
Boxing
- Let’s understand Boxing with a C# programming code :
Csharp
using System;
class GFG {
static public void Main()
{
int num = 2020;
object obj = num;
num = 100;
System.Console.WriteLine
("Value - type value of num is : {0}", num);
System.Console.WriteLine
("Object - type value of obj is : {0}", obj);
}
}
|
Output:
Value - type value of num is : 100
Object - type value of obj is : 2020
Unboxing In C#
- The process of converting a Reference Type variable into a Value Type variable is known as Unboxing.
- It is an explicit conversion process.
- Example :
int num = 23; // value type is int and assigned value 23
Object Obj = num; // Boxing
int i = (int)Obj; // Unboxing
- Description : We declare a Value Type variable num, which is of the type int and assign it with integer value 23. Now, we create a Reference Type variable obj of the type Object, in which we box the variable num. Now, we create a Value Type integer i to unbox the value from obj. This is done using the casting method, in which we explicitly specify that obj must be cast as an int value. Thus, the Reference Type variable residing in the heap memory is copied to stack as shown in below figure :
Unboxing
- Let’s understand Unboxing with a C# programming code :
Csharp
using System;
class GFG {
static public void Main()
{
int num = 23;
object obj = num;
int i = ( int )obj;
Console.WriteLine("Value of ob object is : " + obj);
Console.WriteLine("Value of i is : " + i);
}
}
|
Output:
Value of ob object is : 23
Value of i is : 23
- In cases such as unboxing of a null object or casting the object as an incompatible data type, the program throws exceptions.
Last Updated :
04 Jun, 2022
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...