I have a class that is similar to this:
public class Int16_2D
{
public Int16 a, b;
public override bool Equals(Object other)
{
return other is Int16_2D &&
a == ((Int16_2D)other).a &&
b == ((Int16_2D)other).b;
}
}
This works in HashSet<Int16_2D>. However in Dictionary<Int16_2D, myType>, .ContainsKey returns false when it shouldn’t. Am I missing something in my implementation of ==?
You need to override
GetHashCode(). The fact that it works withHashSet<T>is probably just a lucky coincidence.Both collections use the hash code obtained from
GetHashCodeto find a bucket (ie. list of objects), where the object should be placed. Then it searches that bucket to find the object, and usesEqualsto ensure equality. This is what gives the nice fast lookup properties of the Dictionary and HashSet. However, this also means, that ifGetHashCodeis not overridden so that it corresponds to the typesEqualsmethod, you will not be able to find such an object in one of the collections.You should, almost always, implement both
GetHashCodeandEquals, or none of them.