How to: Use safe_cast and Unboxing
Important This document may not represent best practices for current development, links to downloads and other resources may no longer be valid. Current recommended version can be found here. ArchiveDisclaimer

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.

// 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() {
© 2015 Microsoft