Boxing (C++/CX)

Boxing is wrapping a value type variable such as Windows::Foundation::DateTime—or a fundamental scalar type such as int—in a ref class when the variable is passed to a method that takes Platform::Object^ as its input type.

Although you don't have to explicitly box a variable to pass it to a method parameter of type Platform::Object^, you do have to explicitly cast back to the original type when you retrieve values that have been previously boxed.

Object^ obj = 5; //scalar value is implicitly boxed 
int i = safe_cast<int>(obj); //unboxed with explicit cast. 

C# and Visual Basic support the concept of nullable value types. In C++/CX, you can use the Platform::IBox<T> type to expose public methods that support nullable value type parameters. The following example shows a C++/CX public method that returns null when a C# caller passes null for one of the arguments.

// A WinRT Component DLL
namespace BoxingDemo
{
    public ref class Class1 sealed
    {
    public:
        Class1(){}
        Platform::IBox<int>^ Multiply(Platform::IBox<int>^ a, Platform::IBox<int>^ b)
        {
            if(a == nullptr || b == nullptr)
                return nullptr;
            else
                return ref new Platform::Box<int>(a->Value * b->Value);
        }
    };

In a C# XAML client, you can consume it like this:

// C# client code
    BoxingDemo.Class1 obj = new BoxingDemo.Class1();
    int? a = null;
    int? b = 5;
    var result = obj.Multiply(a,b); //result = null
Show:
© 2014 Microsoft