Boxing and Unboxing

Boxing and Unboxing

 

 

Boxing and unboxing enable value types to be treated as objects. Boxing a value type packages it inside an instance of the Object reference type. This allows the value type to be stored on the garbage collected heap. Unboxing extracts the value type from the object. In this example, the integer variable i is boxed and assigned to object o.

   
int i = 123;
object o = (object)i;  // boxing

The object o can then be unboxed and assigned to integer variable i:

   
o = 123;
i = (int)o;  // unboxing
Boxing is used to store value types in the garbage-collected heap. Boxing is an implicit conversion of a value 
type to the type object or to any interface type implemented by this value type. Boxing a value type allocates 
an object instance on the heap and copies the value into the new object. 
Consider the following declaration of a value-type variable:
        
        
        
        
   
int i = 123;

The following statement implicitly applies the boxing operation on the variable i:

   
object o = i;  // implicit boxing
int i = 123;
object o = (object)i; // explicit boxing
 
Example:

This example converts an integer variable i to an object o by using boxing. Then, the value stored in the variable

i is changed from 123 to 456. The example shows that the original value type and the boxed object use separate

memory locations, and therefore can store different values.

 

class TestBoxing
{
    static void Main()
    {
        int i = 123;
        object o = i;  // implicit boxing

        i = 456;  // change the contents of i

        System.Console.WriteLine("The value-type value = {0}", i);
        System.Console.WriteLine("The object-type value = {0}", o);
    }
}
Output:

The value-type value = 456

The object-type value = 123

Unboxing is an explicit conversion(只能explicit转换) from the type object to a value type or from an interface type to a value type that

implements the interface. An unboxing operation consists of:

  • Checking the object instance to make sure that it is a boxed value of the given value type.

  • Copying the value from the instance into the value-type variable.

Example:

 

class TestUnboxing
{
    static void Main()
    {
        int i = 123;
        object o = i;  // implicit boxing

        try
        {
            int j = (short)o;  // attempt to unbox

            System.Console.WriteLine("Unboxing OK.");
        }
        catch (System.InvalidCastException e)
        {
            System.Console.WriteLine("{0} Error: Incorrect unboxing.", e.Message);
        }
    }
}

Output:

Specified cast is not valid. Error: Incorrect unboxing.

 

If you change the statement:

int j = (short)o;

to:

int j = (int)o;

 

the conversion will be performed, and you will get the output:

Unboxing OK.

 

你可能感兴趣的:(object,Integer,interface,reference,output,Types)