5 Years
Discussion Span
Last Post by Ketsuekiame

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

Edited by Mitja Bonca: n/a


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

Edited by JOSheaIV


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.

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.