Search code examples
c++-clitypesdetection

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.


Solution

  • 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
    }