Boxing and Unboxing

Boxing is the process of converting a value type such as a structure into an object or a reference type. Unboxing is the opposite the opposite process and converts reference types to value types.   Example 1 demonstrates boxing.

namespace BoxingAndUnboxingDemo
{
    struct MyStruct
    {
        public int Number { get; set; }
    }
 
    class Program
    {
        public static void Main()
        {
            MyStruct valueType = new MyStruct(); 
            valueType.Number = 10;               
            object refType = valueType;          
        }
    }
}

Example 1 – Boxing Demo

 We created a structure named MyStruct and provide a property for testing purposes. To box a value type, simple assign it into an object variable. The refType contains an address to a MyStruct type and not the address of the original variable valueType. This can be shown by unboxing the refType back into a value type MyStruct.

MyStruct valueType2 = (MyStruct)refType;

We use casting to convert the reference type refType variable back into a MyStruct value type variable.