C# | Boxing And Unboxing
Prerequisite : Data Types in C#
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 :
- Let’s understand Boxing with a C# programming code :
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 :
- Let’s understand Unboxing with a C# programming code :
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.