Introduction

In C#, boxing and unpacking are crucial ideas. Value types (int, char, etc.), Reference types (object), and Pointer types are the three forms of data in the C# type system. In essence, Unboxing does the opposite of Boxing, which transforms a Value Type variable into a Reference Type variable. A unified view of the type system, where a value of any type can be considered as an object, is made possible via boxing and unboxing.

Boxing

Boxing is the process of changing a Value Type (char, int, etc.) variable to a Reference Type (object).

The implicit conversion procedure known as "boxing" takes advantage of object type (supertype).

Reference type variables are kept in Heap memory, whereas Value type variables are always kept in Stack memory.

Example

int rank = 123;
object objRank  = rank; //boxing

Explanation

Initially, we create a Value Type variable rank of type int and set its initial value to 123. We now construct a Reference Type variable of type Object called objRank and give it a rank. The Value Type variable rank is implicitly copied and saved in the Reference Type variable objRank as a result of this assignment.

int rank = 123;
object objRank = rank; //boxing

//rank value change
rank = 99;

Console.WriteLine("Value - type value of rank is : {0}", rank);
Console.WriteLine();
Console.WriteLine("Object - type value of objRank is : {0}", objRank);

Int rank

Unboxing

Unboxing is the process of changing a Reference Type variable into a Value Type variable.

There is a clear conversion procedure.

int rank = 123;       

object objRank = rank;    // Boxing
int rnk = (int)ObjRank;   // Unboxing

Explanation

An integer value of 123 is assigned to the Value Type variable rank, which we declare and declare as having the type int. We now box the number rank in a Reference Type variable of type Object, called objRank. In order to unbox the value from objRank, we now create a Value Type integer rank. Using the casting technique, we specifically state that the object must be cast as an int value in order to accomplish this. As a result, the Reference Type variable from heap memory is copied to stack memory.

int rank = 123;
object objRank = rank; //boxing

//unboxing
int rnk = (int)rank;

Console.WriteLine("Value - type value of rnk is : {0}", rnk);
Console.WriteLine();
Console.WriteLine("Object - type value of objRank is : {0}", objRank);

Obj rank

Important Things to Consider When Boxing and Unboxing C#

Good Techniques:

We learned the new technique and evolved together.

Happy coding!