2

I'm using Linq-to-Sql to query a SQL Server database. This query returns a List of an entity in my database. My underlying data is NOT changing.

Once I have received the List, I call GetHashCode on it in order to test for equality. Oddly, the hash value is always different. Why would it always be different?

Thank you,

1
  • Keep in mind that even if you override GetHashCode to be based on the contents, as the answers state, you'll still need to deal with collisions, which are objects that have different values but resolve to the same hash code. You won't be able to have a collision-free hash with that type of data (ever), you can only reduce the collision rate. You need to use Equals to ensure objects with the same hash are really the same. Commented Dec 12, 2012 at 16:44

2 Answers 2

5

Are different beacuse they are different object references.

You need to override Equals() and GetHashCode() for your object, based on the object data, if you want to behave in that way.

Here you have an example about how to do it, and here a blog post about the guidelines overriding the GetHashCode() method. Hope it helps.

class TwoDPoint : System.Object
{
    public readonly int x, y;

    public TwoDPoint(int x, int y)
    {
        this.x = x;
        this.y = y;
    }

    public override bool Equals(System.Object obj)
    {
        if (obj == null) return false;

        TwoDPoint p = obj as TwoDPoint;
        if (p == null) return false;

        // Return true if the fields match
        return (x == p.x) && (y == p.y);
    }

    public override int GetHashCode()
    {
        return x ^ y;
    }
}

As Servy said in his comment, keep in mind that even overriding GetHashCode() method, you won't be able to have a collision-free hash with that type of data (ever), you can only reduce the collision rate. You need to use Equals() to ensure objects with the same hash are really the same

Sign up to request clarification or add additional context in comments.

Comments

2

Did you override GetHashCode()? If not the default implementation is to give you a hash code based on the reference of the list. It will not have anything to do with the contents of the list.

So two different instances means two different hash codes.

To check for list equality override Equals (and GetHashCode()) on your entity class and use SequenceEqual on the list.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.