int x=5;
int y=10;
object o1=x;
object o2=y

then how we can compare o1 and o2 (=,<,>,<=,>=)

Recommended Answers

All 6 Replies

Use GetHashCode() method.


In C#, for reference types, the '==' operator compares the references to see if they reference the same object. The Equals() method compares the internal values to see if they have the same values. So in this case you can use the Equals() method

if (o1.Equals(o2)) { 
    // code here

In comparing, you can only use two types of operators: != (not equal) and == (equl).
You cannot use <=, >= becuase these are for numeric comparations.

Or an example from Adapost (which in my opinion is a great one - HashCode is some of a unique key of the value), which you can write like:

int a = 5;
int b = 5;
if (a.GetHashCode().Equals(b.GetHashCode()))

Or Momerath`s example code (in upper post).

if(o1 == o2)
    //objects same

Hashcode does NOT compare equality!!!!!!
If two objects' Hashcodes have the same value then they MIGHT be the same but you still have to compare them.
If the two Hashcodes are different then they cannot be equal and there is no need to compare them further. That is the use for Hashcode - just reducing the number of compares that need to be performed.

I will also advise not to use the hash code as there is a risk of having the values not functioning correclty. From the MSDN website

The default implementation of the GetHashCode method does not guarantee unique return values for different objects. Furthermore, the .NET Framework does not guarantee the default implementation of the GetHashCode method, and the value it returns will be the same between different versions of the .NET Framework.

So just a heads up. I would probably go with Momerath's example. However do note (and it I understand it correctly), Equals() is only good for when you are comparing same objects

Whilst you can call Equals on your class, this will typically tell you if the object reference is the same.

MyObject x = new MyObject(5);
MyObject y = new MyObject(5);
MyObject z = y;

x.Equals(y); // False
x.Equals(z); // False
y.Equals(z); // True

To do your own comparison you will need to overide the Equals method.

Additionally, if you want to do less than or greater than comparison, you will need to write an operator overload.

public static Boolean operator >=(MyObject a, MyObject b)
    return a.Value >= b.Value;

public static Boolean operator <=(MyObject a, MyObject b)
    return a.Value <= b.Value;

You can do the same with the < and > operators also.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, learning, and sharing knowledge.