Earlier I asked if using as
in C# was safe (i.e. won't blow up): Is using "as" in C# a safe way of casting?
I liked the answer and ended up using something based off of it:
Foo x = y as Foo;
if (x != null)
{
...
}
But now I am converting my C# code to C++/CLI (due to a dependance issue..) so questions is..
I'm looking for the C++/CLI equivalent to "as", that is safe and won't blow up at runtime if not correct type. Can anyone suggest a cast that meets my needs? (please provide an example if you can)
Thanks!
Type casting in C refers to converting one data type to some other data type using cast operator. The cast operator is used to transform a variable into a different data type temporarily. Implicit type conversion is done automatically by the compiler, without being specified by the user, when there is more than one data type in an expression.
A safe_cast boxes a value type variable that's on the native stack so that it can be assigned to a variable on the garbage-collected heap. The next sample shows that boxing has priority over a user-defined conversion in a safe_cast operation.
Casting means moving data from one data type to another data type. The below code refers to the explicit casting, which means we need to specify basically which data type you want to convert. Implicit casting means from one data type to another data type without giving any type of conversion.
However, casts are sometimes required, and not all casts are equally dangerous. One effective use of a cast is when your code performs a narrowing conversion and you know that the conversion doesn't cause your program to produce incorrect results.
The C++ way to do such a thing is dynamic_cast
. I don't know if it's the same for managed references as unmanaged references, MSDN had very little information on it.
This may be helpful: http://msdn.microsoft.com/en-us/library/85af44e9
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With