CSharp - Boxing and Unboxing

Introduction

Boxing is the process of converting a value-type to a reference-type, which can be either the object class or an interface.

In the following code, we box an int into an object:

int x = 1;
object obj = x;           // Box the int

Unboxing is the operation of casting the object back to the original value type:

int y = (int)obj;         // Unbox the int

Unboxing requires an explicit cast.

C# throws an InvalidCastException if the value type does not match the object type.

For instance, the following throws an exception, because long does not exactly match int:

object obj = 9;           // 9 is inferred to be of type int
long x = (long) obj;      // InvalidCastException

You change the above code to the following:

object obj = 9;
long x = (int) obj;

The following code shows how to unbox a double value to int.

object obj = 3.5;              // 3.5 is inferred to be of type double
int x = (int) (double) obj;    // x is now 3

Demo

using System;
class MainClass//from ww w.  java  2s .  c  o m
{
   public static void Main(string[] args)
   {
        object obj = 3.5;              // 3.5 is inferred to be of type double
        int x = (int) (double) obj;    // x is now 3

        Console.WriteLine(x);
   }
}

Result

Related Topics