Compare 2 objects using type casting

Lets say I have the following:

int a = 5, b = 2;
object o1 = a;
object o2 = b;

And I want do do

if(o1 == o2) doSomething();

Obviously this doesn't work b/c o1 and o2 are reference objects. But how can I type cast them so it performs the correct comparison

I tried this:

Type type1 = o1.GetType();
Type type2 = o2.GetType();

if((type1)o1 == (type2)o2) doSomething();

But I get a compile error saying:

"The type or namespace 'type1' could not be found"

Does anybody know how to do this correctly


Answer this question

Compare 2 objects using type casting

  • Tom Hollander

    Instead of using the == operator you can use the equals method. Like this:

    if(o1.Equals(o2) ) doSomething();



  • tfrazier

    Hi, soconne

    a and b are int type, all value types are stored in stack while reference types in heap.

    When you try to cast from value type to reference type, it will box (copy) the value stored in stack into heaps and remain a reference to that copy value in stack.

    So, if you want to compare with two boxing objects, you should use equals method to compare their value but not their reference address value.

    Hope that will be clear, thank you.



  • Jun_1111

    More to the point type1 and type2 are variables not types. You code would have to read:

    if((Type)o1 == (Type)o2) doSomething();

    Of course, since they are both already Type's you could just use:

    if(o1 == o2) doSomething();



  • Compare 2 objects using type casting