Use "external" GetHashCode and Equals for dictionary

I would like to use the class as a key in a dictionary that does not override Equals or GetHashCode. This is a class from an external library that I do not want to modify.

So I'm wondering if I can use custom "GetHashCode" / "Equals" to use for only one dictionary? I was wondering if something like C ++ std :: maps is 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 comparisons.

I do not want to deduce from the class, because objects are created externally using an existing class.

I could create a class that contains the source class, but which modifies access to the Dictionary.

Thanks for your ideas!

+4
source share
3 answers

Of course, you can implement IEqualityComparer<T> and pass this to the Dictionary<,> constructor . That is the purpose of this constructor :)

For instance:

 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()); 
+5
source

You can pass the custom IEqualityComparer<TKey> to the Dictionary<TKey,TValue> . The equality comparator must implement Equal and GetHashCode .

 var dict = new Dictionary<MyKey,MyValue>(new MyKeyEqualityComparer()); 
+2
source

You can use the dictionary constructor (Int32, IEqualityComparer) ,

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

Where

comparer :

for use when comparing keys

Almost

  • you define a type that implements this interface
  • pass it to this ctor, so the method of this class is used to identify the equality of the dictionary keys.

It seems that you want to.

+1
source

All Articles