Was this page helpful?
Your feedback about this content is important. Let us know what you think.
Additional feedback?
1500 characters remaining
Collapse the table of content
Expand the table of content


Visual Studio .NET 2003

Performs the specified cast or throws an exception if the cast fails.

__try_cast < type-id > ( expression )


The __try_cast keyword (similar in behavior to dynamic_cast) provides support for automatically throwing an exception (of type System::InvalidCastException) whenever the specified casting operation fails. For more information on __try_cast, see 7.5.2 __try_cast.

The __try_cast keyword can be used during the testing phase of your application, automatically alerting you to possible casting failures.


In the following example, an attempt to cast a pointer (of Derived type) to another pointer (of MoreDerived type) is made. If the cast fails, it is caught and reported by the catch block:

// keyword__try_cast.cpp
// compile with: /clr
#using <mscorlib.dll>
using namespace System;

__gc struct Base {};

__gc struct Derived : Base {};

__gc struct MoreDerived : Derived {};

int main()
   Base*bp = new Derived;
       MoreDerived* mdp = __try_cast<MoreDerived*>(bp);
       Console::WriteLine("Could not cast 'bp' to MoreDerived*");
   return 0;


Could not cast 'bp' to MoreDerived*

See Also

Managed Extensions for C++ Reference | __gc | dynamic_cast | Handling Exceptions Using Managed Extensions for C++ | C++ Keywords

© 2015 Microsoft