boxing and unboxing can happens with with value types and reference types.

Object (System.Object) is the ultimate base class for all types.

Since Object is a class, it is a reference type.

Converting a value type to object type (i.e., reference type) is called boxing, and the reverse procedure is known as unboxing.

Boxing stores the copied value into that object.

Here is an example of boxing:

int i = 10;
object o = i;//Boxing

Now consider the reverse scenario. If you try to write code like this:

object o = i;//Boxing
int j = o;//Error

To avoid this, we need to use unboxing, like this:

object o = i;
int j = (int)o; //Unboxing

Boxing is implicit. We do not need to write code like this:

int i = 10;
object o = (object)i;
//object o=i; is fine since Boxing is implicit.

Related Topic