Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Safe casting in C++/CLI - equivalent to C#'s "as"?

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!

like image 498
developer Avatar asked Jul 21 '11 20:07

developer


People also ask

What is type type casting in C?

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.

What is a safe_cast in C++?

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.

What is the difference between explicit and implicit casting in C++?

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.

Are all casts in C dangerous?

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.


2 Answers

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.

like image 54
Puppy Avatar answered Oct 23 '22 03:10

Puppy


This may be helpful: http://msdn.microsoft.com/en-us/library/85af44e9

like image 43
Ajay Avatar answered Oct 23 '22 03:10

Ajay