Philipp
Philipp

Reputation: 11813

Use "external" GetHashCode and Equals for 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!

Upvotes: 4

Views: 466

Answers (3)

Olivier Jacot-Descombes
Olivier Jacot-Descombes

Reputation: 112342

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());

Upvotes: 2

Tigran
Tigran

Reputation: 62246

You can use Dictionary Constructor (Int32, IEqualityComparer),

public Dictionary(
    int capacity,
    IEqualityComparer<TKey> comparer
)

where

comparer is:

implementation to use when comparing keys

In practise

  • you define a type that implements that interface
  • pass it to this ctor , so the method of that class are useed for equality identification of the keys of the dictionary.

Seems what you want.

Upvotes: 1

Jon Skeet
Jon Skeet

Reputation: 1500495

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());

Upvotes: 5

Related Questions