2

I want to use a custom generic class as a key in a dictionary. How should I override Equals and GetHashCode?

Eg,

public class SomeKey<T,V>
{
    public T Value1 { get; set; }
    public V Value2 { get; set; }

    public SomeKey(T val1, V val2)
    {
        this.Value1 = val1;
        this.Value2 = val2;
    }

    public override bool Equals(SomeKey<T,V> otherKey)
    {
        //whats the best option here?
    }

    public override int GetHashCode()
    {
        //whats the best option here?
    }
}

Thanks

David Heffernan
  • 601,492
  • 42
  • 1,072
  • 1,490
MalcomTucker
  • 7,407
  • 14
  • 72
  • 93

2 Answers2

5

Equality is simple: test for Value1 and Value2 being equal.

For the hash code the simplest approach is to use xor to combine the hash codes from Value1 and Value2.

public override bool Equals(SomeKey<T,V> otherKey)
{
    return Value1.Equals(otherKey.Value1) && Value2.Equals(otherKey.Value2);
}

public override int GetHashCode()
{
    return Value1.GetHashCode() ^ Value2.GetHashCode();
}

There are lots of alternative ways of calculating the hash code. If performance is a bottleneck then you should consider something more tailored than xor.

For example, Stack Overflow offers these links (and many more):

Community
  • 1
  • 1
David Heffernan
  • 601,492
  • 42
  • 1,072
  • 1,490
1

You should override it in a way that GetHashcode reliably returns the same value for the same object, and Equals to always return true for the same objects. The msdn has some advices for implementing GetHashcode (the remarks section).

Femaref
  • 60,705
  • 7
  • 138
  • 176