Alex Rivera | Logout

c# How to find if two objects are equal

Asked 2010-05-27T10:46:25.080
32

I want to know the best way to compare two objects and to find out if they're equal. I'm overriding both GethashCode and Equals. So a basic class looks like:

public class Test
{
    public int Value { get; set; }
    public string String1 { get; set; }
    public string String2 { get; set; }

    public override int GetHashCode()
    {
        return Value ^ String1.GetHashCode() ^ String2.GetHashCode();
    }

    public override bool Equals( object obj )
    {
        return GetHashCode() == obj.GetHashCode();
    }
}

So for testing purposes I created two objects:

Test t = new Test()
{
    Value = 1,
    String1 ="One",
    String2 = "One"
};

Test t2 = new Test()
{
    Value = 1,
    String1 = "Two",
    String2 = "Two"
};

bool areEqual = t.Equals( t2 );

In testing this areEqual returns true event though both objects are different. I realise this is because String1 and String2 are the same value in each object and thus cancels each other out when hashing.

Is there a better way off hashing object that the method I have that will resolve my issue?

Edit
Report

1 Answer

2

For any two objects, object equality implies hash code equality, however, hash code equality does not imply object equality. From Object.GetHashCode on MSDN:

A hash function must have the following properties:

If two objects compare as equal, the GetHashCode method for each object must return the same value. However, if two objects do not compare as equal, the GetHashCode methods for the two object do not have to return different values.

In other words, your Equals is written wrong. It should be something like:

public override bool Equals(object obj)
{
    Test other = obj as Test;
    if (other == null)
        return false;

    return (Value == other.Value)
        && (String1 == other.String1)
        && (String2 == other.String2);
}

GetHashCode is good for collections (like Dictionary<K, V>) to quickly determine approximate equality. Equals is for comparing if two objects really are the same.

answered 2010-05-27T10:53:47.573

Your Answer