How to: Downcast with safe_cast
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: Downcast with safe_cast

A downcast is a cast from a base class to a class derived from the base class. A downcast is only safe if the object addressed at runtime is actually addressing a derived class object. Unlike static_cast, safe_cast performs a dynamic check and throws InvalidCastException if the conversion fails.

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

interface class A { void Test(); };

ref struct B : public A {
   virtual void Test() { 
      Console::WriteLine("in B::Test()");

   void Test2() { 
      Console::WriteLine("in B::Test2()");

ref struct C : public B {
   virtual void Test() override { 
      Console::WriteLine("in C::Test()");

interface class I {};

value struct V : public I {};

int main() {
   A^ a = gcnew C();
   B^ b = safe_cast<B^>(a);

   V v; 
   I^ i = v;   // i boxes V
   V^ refv = safe_cast<V^>(i); 
   Object^ o = gcnew B;
   A^ a2= safe_cast<A^>(o);


in C::Test()
in C::Test()
in B::Test2()
© 2015 Microsoft