Core C#

Boxing and Unboxing

This C# Reference page is for understanding boxing and unboxing for value and reference types in Microsoft's C# programming language. Boxing refers to the process of putting a value type inside of a reference type, while unboxing refers to creating a corresponding value type from a boxed reference type. The value of the variable remains the same. Hoowever, the type is changed via boxing and unboxing.

Program.cs

using System;

namespace XoaX {
    class Program {
        static void Main(string[] args) {
            int iInt = 70;
            Console.WriteLine("iInt = " + iInt);
            // Box iInt inside a reference type
            object qObject = iInt;
            Console.WriteLine("qObject = " + qObject);
            // Unbox qObject to a value type via a cast back to its original type.
            int iUnboxed = (int)qObject;
            Console.WriteLine("iUnboxed = " + iUnboxed);

            // Note that an improper unboxing to a different type will cause an exception
            try {
                // This cast perfectly valid, but next unboxing throws an exception that gets caught
                double dX = (int)iInt;
                Console.WriteLine("dX = " + dX);
                // Attempt to unbox the object to a double. Note that the conversion is well-defined.
                double dY = (double)qObject;
                System.Console.WriteLine("This doesn't print bacause of the exception.");
            } catch (System.InvalidCastException e) {
                System.Console.WriteLine("Exception: " + e.Message);
            }
        }
    }
}
 

Output

iInt = 70
qObject = 70
iUnboxed = 70
dX = 70
Exception: Specified cast is not valid.
Press any key to continue . . .
 
 

© 2007–2024 XoaX.net LLC. All rights reserved.