I think this could be a common question but I failed to find any post about it.
I'm writing some pseudo code below. If you want to compile the code, please just ignore this post.
So say two classes: one base class and one child class. NOTE: both classes have override Equals() and GetHashCode() function to ensure equality with same property.
public class A // A has a string property of name
public class B:A // B has a string property of title
var a = new A{name = "bob"};
var b = new B{name = "bob", title = "em"};
Some code have a dictionary based on A
var dict = new Dictionary<A>();
Doing some adding stuff, for instance,
dict.Add(a);
However, the lookup function will raise KeyNotFoundException if i use a derived class searching with/o type cast
dict[b];
Dictionary will calculate the hashcode of B instead of A and raised the exception according to that.
A simple and awkward solution is to create a new instance of A based on B's property.
dict[new A{name = b.name}];
I wonder if there is any better solution?
Try creating an EqualityComparer, and pass an instance of it in the constructor of the dictionary.
class AEqualityComparer : IEqualityComparer<A>
{
public bool Equals(A x, A y)
{
return x.Equals(y);
}
public int GetHashCode(A obj)
{
return obj.GetHashCode();
}
}
var dict = new Dictionary<A, object>(new AEqualityComparer());