Boxing And Unboxing In C#

In a sentence, Boxing is the process of converting value type to reference type.

Ex

int i=6; // Integer ‘i' is value type  
Object o = i; // Object ‘o’ is reference type   

Unboxing is the reverse process of the boxing like converting reference type to value type.

Object o = 6; // Object ‘o’ is reference type  
Int i= (int)o; // Integer ‘i' is value type  

Now here the another question in mind,

  • What is Value and Reference type?
  • What all are the value type and reference types?

Now start with:

What is Value and Reference type?

Value and Reference type are the two data types in c#.

Value type

Those variable which can contain the data directly that all falls in value type data type. As above example,

int i=6;  

Here we are assigning the value directly to the variable.

Memory representation

Boxing And Unboxing In C#

Diagram Desc

In above diagram int I address xxxx001 is directly pointing to the value which is here 6,

Ex for some value type variables,

Boxing And Unboxing In C#

Reference type

Those variables which contain address[Reference] of the data instead of data that all falls in Reference type data type.

As Above Example,

Object o = 6;  

Here we are assigning the value in the object which is referencing the address of the data 6.

Memory representation

Boxing And Unboxing In C#

Diagram Desc: In above picture ‘xxxx0002’ is the address of object ‘o’ which is not containing the direct value instead it is stored address of value ‘6’ which is ‘xxxx0003’.

Examples of some Reference type variables:

Boxing And Unboxing In C#

Thanks for reading!!

Your comments and compliments are highly appreciated.... :)