GustavoPollitzer

Hello,

I am migrating code from the old Managed Syntax to the new C++/CLI syntax. To do this transformation I followed the hints explained in several articles of the MSDN.
But what I didn't find there is how to convert the __try_cast operator when the type being casted is unmanaged.

Does I have to use dynamic_cast and append an assertion Or there is a special operator like safe_cast but for unmanaged types

Thank you in advance.



Re: Visual C++ Express Edition migration of the __try_cast operator

Mike Danes

Interesting. __try_cast was supposed to work with managed types, I see no reference anywhere about it being used with unmnaged types. Testing (in VC++ 2005) shows that __try_cast with used with an unmanaged type generates a dynamic_cast so the rules seem to be:

  • use safe_cast instead of __try_cast with managed type
  • use dynamic_cast instead of __try_cast with unmanaged type




Re: Visual C++ Express Edition migration of the __try_cast operator

GustavoPollitzer

uhmmm.... But dynamic_cast don't throw an exception when a pointer is casted and fails. It returns NULL instead;





Re: Visual C++ Express Edition migration of the __try_cast operator

Mike Danes

Yes, but that's what __try_cast seem to do when used with an unmanaged type (at least in VC++ 2005 with /clr:oldSyntax).





Re: Visual C++ Express Edition migration of the __try_cast operator

GustavoPollitzer

You are right. I tested it on Visual Studio 2003 and there it returns NULL too.

I also read the __try_cast documentation again, and it sais nothing about returning NULL when the cast fails and the type is unmanaged. The following is what the managed extensions for C++ specifications says:

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.