Firstly, I'm using the GetHashCode
algorithm described, here. Now, picture the following (contrived) example:
class Foo
{
public Foo(int intValue, double doubleValue)
{
this.IntValue = intValue;
this.DoubleValue = doubleValue;
}
public int IntValue { get; private set; }
public double DoubleValue { get; private set; }
public override int GetHashCode()
{
unchecked
{
int hash = 17;
hash = hash * 23 + IntValue.GetHashCode();
hash = hash * 23 + DoubleValue.GetHashCode();
return hash;
}
}
}
class DerivedFoo : Foo
{
public DerivedFoo(int intValue, double doubleValue)
: base(intValue, doubleValue)
{
}
}
If I have a Foo
and a DerivedFoo
with the same values for each of the properties they're going to have the same hash code. Which means I could have HashSet<Foo>
or use the Distinct
method in Linq and the two instances would be treated as if they were the same.
I'm probably just misunderstanding the use of GetHashCode
but I would expect these the two instances to have different hash codes. Is this an invalid expectation or should GetHashCode
use the type in the calculation? (Or should DerivedClass
also override GetHashCode
)?
P.S. I realize there are many, many questions on SO relating to this topic, but I've haven't spotted one that directly answers this question.