I've a project where I am extensively using the generic C# dictionary. I require composite keys, so I've been using tuples as keys. At some point I was wondering whether it would be beneficial to use a custom class which caches the hash code:
public class CompositeKey<T1, T2> : Tuple<T1, T2>
{
private readonly int _hashCode;
public CompositeKey(T1 t1, T2 t2) : base(t1, t2)
{
_hashCode = base.GetHashCode();
}
public new int GetHashCode()
{
return _hashCode;
}
}
I used new
instead of override
because I thought it would not make a difference for this test, since I was defining the dictionary using the concrete type:
var dict = new Dictionary<CompositeKey<string, int>, int>();
I noticed, however, that my custom GetHashCode
method is not called at all. When I changed new
to override
it got called as expected.
Can somebody explain why the hidden GetHashCode
method is not called? I would expect this behavior if I would define the dictionary like this
var dict = new Dictionary<Tuple<string, int>, int>();
but not if I specify the CompositeKey
type explicitly as in my example.
P.S. I know that hiding the GetHashCode
method is probably not a good idea.