I would like to use a class as key in a Dictionary which does not override Equals nor GetHashCode. It's a class from an external library which I don't want to modify.
So I am wondering if I can use custom "GetHashCode"/"Equals" implemantiotns just for one Dictionary? I was wondering if something like with C++ std::maps was possible
template < class Key,                      // map::key_type
           class T,                        // map::mapped_type
           class Compare = less<T>,        // map::key_compare
           class Alloc = allocator<T> >    // map::allocator_type
           > class map;
where Compare can be used to define custom comparison.
I don't want to derive from the class because the objects are created outside using the existing class.
I could create a class which contains the original class, but that changes the access to the Dictionary.
Thanks for your ideas!
Sure - you can implement IEqualityComparer<T> and pass that into the Dictionary<,> constructor. That's precisely the purpose of that constructor :)
For example:
public FooByNameEqualityComparer : IEqualityComparer<Foo>
{
    public int GetHashCode(Foo foo)
    {
        return foo.Name.GetHashCode();
    }
    public bool Equals(Foo x, Foo y)
    {
        return x.Name == y.Name;
    }
}
...
Dictionary<Foo, int> map = new Dictionary<Foo, int>(new FooByNameComparer());
                        You can pass a custom IEqualityComparer<TKey> to the constructor of the Dictionary<TKey,TValue>. The equality comparer must implement Equal and GetHashCode.
var dict = new Dictionary<MyKey,MyValue>(new MyKeyEqualityComparer());
                        If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With