C# Boxing Unboxing

In most cases, C# data type includes value type and reference type. A value type can be converted to a reference type which it inherits from or implements. We call this process boxing and the reverse operation is called unboxing. Structs are value types and derived from System.Objects so they can be boxing as well. Boxing is implicit and unboxing is explicit.

Example 01-74-01

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
using System;

class Program
{
    static void Main()
    {
        int i = 100;
        object o = i;   // boxing

        // Other codes
        i = (int)o;     // unboxing
        Console.WriteLine("i={0}", i);
        Console.Read();
    }
}

Output

i=100

Explanation

  • Line 7: Declare an integer variable i with its initial value 100.
  • Line 8: Boxing because int is the alias of System.Int32 which is a struct.
  • Line 11: Unboxing explicitly by preforming a cast.
  • Line 12: Output the value of i.

Example 01-74-02

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
using System;

struct Rectangle
{
    public int length;
    public int width;

    public override string ToString()
    {
        return "L:" + length + " W:" + width;
    }
}

class Program
{
    static void Main()
    {
        Rectangle r;
        r.length = 10;
        r.width = 6;
        object o = r;   // boxing
        Console.WriteLine("r={0}", o);

        // Other codes
        r = (Rectangle)o;     // unboxing
        Console.WriteLine("r={0}", r);
        Console.Read();
    }
}

Output

r=L:10 W:6
r=L:10 W:6

Explanation

  • Line 3-12: Declare a struct Rectangle.
  • Line 8-11: The method ToString() is overridden to output the field values of the object instead of printing the struct name.
  • Line 18-20: Declare a Rectangle variable r and initialize the fields without using the new operator.
  • Line 21: Boxing because a struct is a value type.
  • Line 22: Output string. At run-time, the most overridden method ToString() defined in the struct is called.
  • Line 25: Unboxing.
  • Line 26: Output the same result as that in line 22.