12

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.

AProgrammer
  • 48,232
  • 8
  • 83
  • 139
Jon Cage
  • 33,172
  • 32
  • 120
  • 206

3 Answers3

28

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
  • 2,450
  • 15
  • 21
  • 1
    It still works in VS2010. I don't have VS2012 so can't comment on the latest VS version. It may be you are not "seeing that typeid member" because autocomplete for C++/CLI was not included in VS2010. – mcdave Sep 12 '12 at 15:00
  • I could even use it in VS2013. – Ozair Kafray Apr 20 '18 at 07:37
9

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
  • 320,708
  • 66
  • 621
  • 623
  • Is there a way to do that with generics rather than templates so that the method can be used in external assemblies? – Jon Cage Mar 10 '10 at 11:14
0

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
  • 4,784
  • 1
  • 16
  • 13