Was this page helpful?
Your feedback about this content is important. Let us know what you think.
Additional feedback?
1500 characters remaining
Export (0) Print
Expand All
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.

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();
   a->Test();
   B^ b = safe_cast<B^>(a);
   b->Test();
   b->Test2();

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

Output

in C::Test()
in C::Test()
in B::Test2()

Community Additions

ADD
Show:
© 2015 Microsoft