title | ms.custom | ms.date | ms.technology | ms.reviewer | ms.suite | ms.tgt_pltfrm | ms.topic | ms.assetid | caps.latest.revision | author | ms.author | manager |
---|---|---|---|---|---|---|---|---|---|---|---|---|
Boxing (C++/CX) | Microsoft Docs |
12/30/2016 |
cpp-windows |
article |
edfb12fa-2a9b-42f6-bdac-d4d76cb8274e |
12 |
ghogen |
ghogen |
ghogen |
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.
[!code-cppcx_boxing#01]
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.
[!code-cppcx_boxing#02]
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
Type System (C++/CX)
Casting (C++/CX)
Visual C++ Language Reference
Namespaces Reference