Boxing and Unboxing in C#

Simply Boxing means the conversion of the value type on the stack to a object type on the heap, similarly the conversion from an object type back to a value type is called as unboxing.

In object oriented programming languages, methods are called using object. Value types such as int is not object, we cannot use that to call methods. But in C# we can do this with the help of Boxing.

Boxing In C#

Value or reference, both can be assigned to an Object without explicit conversion. See following example:

int i=50;

Object obj = i;

We can also use a proper casting in C#

int i = 50;

object obj = (object)i;

important things is also here to mention that boxing creates a copy of the value of I integer to the object obj and now both variable are available but value of obj resides on the heap. This indicates that the value are independent of each other. Consider the following example:

int i = 50;

object obj = i;

i = 40;

output :

// value of I = 40

// value of obj = 50

Unboxing in C#

Simply unboxing is the process of converting the object type back to the value type. Important thing is that we can only unbox a variable that has previously been boxed.

int i = 40;

object obj = i;

int j = (int)obj;



When unboxing, we need to use explicit casting. This is because in the case of unboxing, an object could be cast to any type. Therefore, the cast is necessary for the compiler to verify that it is valid as par the specified value type.

2 thoughts on “Boxing and Unboxing in C#”

  1. teri maa ki choot……balagurusmay textbook say copy paste kiya hai……u r making fool to others..

Comments are closed.