C# Boxing And Unboxing

Boxing

  1. Boxing is the process of converting a value type to a reference type.
  2. CLR(Common Language Runtime) wraps a value inside System. Object instance and stores it on managed heap(memory).
  3. In simple words, boxing is used to store the value type in the garbage collected heap.
  4. Boxing is an implicit conversion of value type to object.

 Example

//.net core 6

int abc = 1000;
object obj = abc;//Boxing
abc = 2000;
Console.WriteLine("Value Of Object = "+ abc);
Console.WriteLine("Value Of Xyz = " + obj);

//Output
Value Of Object = 2000
Value Of Xyz = 1000

In the above example, “abc” is an int(value-type) with a value of “1000”. After that, object ‘obj’ copies value from ‘abc’, i.e boxing.

This statement creates an object reference ‘obj’ on the stack and references a value of type int on the heap.

Unboxing

  1. Unboxing is the process of converting a reference-type to a value-type.
  2. Unboxing is the explicit conversion of an object to a value type.
  3. We can also say that unboxing is the process of retrieving value from a boxed object.
  4. The unboxing operation consists of,
     
    • Checking the object instance to ensure it is a boxed value.
    • Copying a value from an instance to a value-type variable.

Example

//.net core 6

int abc = 5000;
object obj = abc;//Boxing
int xyz = (int)obj;//UnBoxing
Console.WriteLine("Value Of Object = "+ abc);
Console.WriteLine("Value Of Xyz = " + xyz);

//Output
Value Of Object = 5000
Value Of Xyz = 5000

In the above example, ‘abc’ is an int(value-type) with a value of ‘5000’. After that,

object ‘obj’ copies value from ‘abc’, i.e boxing.

This statement creates an object reference ‘obj’ on the stack and references a value of type int on the heap. Following that,

int ‘xyz’ copies the value from object ‘obj,’ i.e. unboxing.

The result of this statement is that it copies the value from the heap and stores it on the stack (into value-type ‘xyz’).

  • Boxing and unboxing degrade the performance, so developers always avoid using it. We can use generics to avoid this.
  • Boxing and unboxing consume more memory and time.
  • Both increase overhead and lack safety measures.

Please do leave a comment if you find it useful. You can find the repository here.


Recommended Free Ebook
Similar Articles