Comparing types of objects???

Hi

In the following code, I am trying to compare the type of object in obj variable with type of typeInt.

int typeInt=0;
int a = 1;
object obj;

obj = (object) a;
if (typeInt.GetType() == obj.GetType())
{
MessageBox.Show("Int returned");
}


I want to make sure if this is the correct way to do it. If not, how else I compare types of two objects

Please advice. Thanks

Pankaj


Answer this question

Comparing types of objects???

  • Ehrick

    Actually, both posts are wrong...

    In darshana's post, "if (obj Is System.Int32)" is not a legal comparison.  It would have to be "if (obj.GetType Is GetType(System.Int32)".

    In my post, "typeInt.GetType.Equals(a)" will not return true for two integers.  It would have to be "typeInt.GetType.Equals(a.GetType)".

    Both methods seem to have the same performance rating.

  • joyhrs

    I think you could just use:

    int typeInt=0; 
    int a = 1;

    if (typeInt.GetType.Equals(a))

    MessageBox.Show("Int returned"); 


  • Leandro Pardo

    Yeah, I made an assumption from VB to C# that wasn't correct...  sorry
  • woodced

    "if (obj is System.Int32)" is a legal comparison. It works.

    But "if (obj.GetType Is GetType(System.Int32)" will not compile. Aren't we speaking c# here 

  • Railmonkey

    if (obj is System.Int32)
    {
    MessageBox.Show("Int returned"); 

    }

  • Comparing types of objects???