Boxing and Unboxing

October9, 2017
by admin

We have looked at the concepts of value type and reference type and type conversions. Let’s now understand what the terms Boxing and Unboxing are.

Boxing is a conversion from value type to reference type and Unboxing is a conversion from reference type to value type. Boxing is an implicit conversion and doesn’t need casting while unboxing is an explicit conversion and need casting. Lets understand this with an example code.

Ex:


  // variables declaration
  int x = 100;
  object y;
  int z;

  // Boxing (implicit conversion)
  y = x;

  // Unboxing (explicit conversion)
  z = (int)y;

In the above code, we first declared three variables x and z with data type ’int’ and y with the data type ’object’.

Note that object data type variable can hold any data type value and is a reference data type while int is a value data type.

Then we assigned a value of x (integer) to the variable y (object). This is an implicit conversion and known as boxing since we are converting a value type to reference type implicitly.

On the next line, we are assigning a value in the object type variable y to integer type variable z. This an explicit conversion which requires casting and known as unboxing, since we are converting reference type back to a value type explicitly.

C# Fundamentals