Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use "external" GetHashCode and Equals for Dictionary

Tags:

c#

dictionary

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!

like image 784
Philipp Avatar asked Feb 18 '23 19:02

Philipp


2 Answers

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());
like image 114
Jon Skeet Avatar answered Mar 02 '23 22:03

Jon Skeet


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());
like image 35
Olivier Jacot-Descombes Avatar answered Mar 02 '23 23:03

Olivier Jacot-Descombes