views:

178

answers:

3

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.

+3  A: 

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++.

Andrew Hare
Is there a way to do that with generics rather than templates so that the method can be used in external assemblies?
Jon Cage
A: 

edit: I will leave this here. But this answer is for C++. Probably not even slightly related to doing this for the CLI.

You need to compile with RTTI(Run Time Type Information) on. Then look at the wikipedia article http://en.wikipedia.org/wiki/Run-time_type_information and search google for RTTI. Should work for you.

On the other hand you might want to have a virtual base class for all your data classes with a member variable that describes what type it is.

mfperzel
+2  A: 

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
}
mcdave
+1/Accept: That's perfect - thanks!
Jon Cage