-1

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
  • 90,369
  • 161
  • 124
  • 175
a new one
  • 59
  • 1
  • 8
  • 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
  • 41,709
  • 14
  • 73
  • 93
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,135
  • 17
  • 37