Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check an object's type in C++/CLI?

Is there a simple way to check the type of an object? I need something along the following lines:

MyObject^ mo = gcnew MyObject();
Object^ o = mo;

if( o->GetType() == MyObject )
{
    // Do somethine with the object
}
else
{
    // Try something else
}

At the moment I'm using nested try-catch blocks looking for System::InvalidCastExceptions which feels ugly but works. I was going to try and profile something like the code above to see if it's any faster/slower/readable but can't work out the syntax to even try.

In case anyone's wondering, this comes from having a single queue entering a thread which supplied data to work on. Occasionally I want to change settings and passing them in via the data queue is a simple way of doing so.

like image 460
Jon Cage Avatar asked Mar 09 '10 16:03

Jon Cage


People also ask

How do you check if an object is a specific type?

To determine whether an object is a specific type, you can use your language's type comparison keyword or construct.

How do you check if an object belongs to a certain class in C++?

C++ has no direct method to check one object is an instance of some class type or not. In Java, we can get this kind of facility. In C++11, we can find one item called is_base_of<Base, T>. This will check if the given class is a base of the given object or not.


2 Answers

You can use MyObject::typeid in C++/CLI the same way as typeof(MyObject) is used in C#. Code below shamelessly copied from your question and modified ...

MyObject^ mo = gcnew MyObject();
Object^ o = mo;

if( o->GetType() == MyObject::typeid )
{
    // Do somethine with the object
}
else
{
    // Try something else
}
like image 100
mcdave Avatar answered Oct 22 '22 22:10

mcdave


You should check out How to: Implement is and as C# Keywords in C++:

This topic shows how to implement the functionality of the is and as C# keywords in Visual C++.

like image 10
Andrew Hare Avatar answered Oct 22 '22 21:10

Andrew Hare