How to: Use safe_cast and Unboxing

Unoxing in defined as a compiler-injected, user-defined conversion. Therefore, safe_cast can be used to unbox a value on the CLR heap.

Unboxing is a user-defined conversion, but unlike boxing, unboxing must be explicitly, which means it must be performed by a static_cast, C-style cast, or safe_cast; unboxing cannot be performed implicitly.

Example

// safe_cast_unboxing.cpp
// compile with: /clr
int main() {
   System::Object ^ o = 42;
   int x = safe_cast<int>(o);
}

The following sample shows unboxing with value types and primitive types.

// safe_cast_unboxing_2.cpp
// compile with: /clr
using namespace System;

interface struct I {};

value struct VI : public I {};

void test1() {
   Object^ o = 5;
   int x = safe_cast<Int32>(o);
}

value struct V {
   int x;
   String^ s;
};

void test2() {
   V localv;
   Object^ o = localv;
   V unboxv = safe_cast<V>(o);
}

void test3() {
   V localv;
   V^ o2 = localv;
   V unboxv2 = safe_cast<V>(o2);
}

void test4() {
   I^ refi = VI();
   VI vi  = safe_cast<VI>(refi);
}

int main() {
   test1();
   test2();
   test3();
   test4();
}

See Also

Reference

safe_cast