0

If I have a dictionary

Dictionary<SomeClass, int> MyDict { get; set; } = ...

how can I override the compare method that gets called when it is evaluating a key?

As in - I want to be in control of which object gets picked when I write

MyDict[SomeClassInstance]
Mark Rotteveel
  • 100,966
  • 191
  • 140
  • 197
a new one
  • 89
  • 1
  • 11
  • 2
    Possible duplicate of [Comparing object used as Key in Dictionary](https://stackoverflow.com/questions/11562996/comparing-object-used-as-key-in-dictionary). [See](https://stackoverflow.com/a/11563134/1797425) this answer as it is what you would need. – Trevor Sep 03 '19 at 17:31

2 Answers2

3

You need to implement an IEqualityComparer<TKey> and pass an instance of this to the dictionary's constructor:

public class MyComparer : IEqualityComparer<object>
{
    public bool Equals(object o1, object o2)
    {
        // implement your way of equality 
    }
    public int GetHashCode(object o)
    {
        // implement a hash method that returns equal hashes for equal
        // objects and well distributed hashes for not-equal objects
    }
}

Dictionary<object, int> myDict = new Dictionary<object, int>(new MyComparer());
René Vogt
  • 43,056
  • 14
  • 77
  • 99
0

You would want to use the constructor that allows you to pass in an instance of IEqualityComparer<TKey>, which would then be used for your key comparisons. I don't believe you can change this after instantiation.

Jonathon Chase
  • 9,396
  • 21
  • 39