Boxing and unboxing

Boxing is the process of casting value type to reference type.

Unboxing casts the reference type to value type.

The following code is boxing the i to object.


using System;

class Program
{
    static void Main(string[] args)
    {

        int i = 0;
        object obj = i;

        Console.WriteLine(obj);
    }
}

The output:


0

The unbox requires an explicit cast.


using System;

class Program
{
    static void Main(string[] args)
    {

        int i = 0;
        object obj = i;
        int j = (int)obj;


        Console.WriteLine(obj);
        Console.WriteLine(j);

    }
}

The output:


0
0
java2s.com  | Contact Us | Privacy Policy
Copyright 2009 - 12 Demo Source and Support. All rights reserved.
All other trademarks are property of their respective owners.