7.5.2 __try_cast

7.5.2 __try_cast

Visual Studio .NET 2003

The Managed Extensions provide a new dynamically checked cast, similar to dynamic_cast, that throws an exception when the cast is unsuccessful:

__try_cast < type-id > ( expression ) 

If a __try_cast fails at runtime, it will throw System::InvalidCastException.

Example

// __gc_pointer13.cpp
// compile with: /clr
#using <mscorlib.dll>
__gc struct Base {};
__gc struct Derived : Base {};
__gc struct MoreDerived : Derived {};

int main() {
   Base*bp = new Derived;
   try {
      MoreDerived *mdp = __try_cast<MoreDerived*>(bp);
   }
   catch(System::InvalidCastException*) {
      System::Console::WriteLine("Could not cast 'bp' to MoreDerived*");
   }
}

Output

Could not cast 'bp' to MoreDerived*

Constraint

  • __try_cast shall not be used on value type pointers including pointers of type Void *.
Show:
© 2016 Microsoft