Search code examples
c#dictionaryuniqueidentityiequatable

C# dictionary uniqueness for sibling classes using IEquatable<T>


I would like to store insances of two classes in a dictionary structure and use IEquatable to determine uniqueness of these instances. Both of these classes share an (abstract) base class. Consider the following classes:

abstract class Foo
{
   ...
}

class SubFoo1 : Foo
{
   ...
}

class SubFoo2 : Foo
{
   ...
}

The dictionary will be delcared: Dictionary<Foo, Bar>

Which classes should be declared as IEquatable? And what should the generic type T be for those declarations? Is this even possible?


Solution

  • Don't declare anything as IEquatable<T>. It's generally a problem when it comes to inheritance and equality, as Marc says.

    Instead, work out what kind of equality you want for the keys in this particular dictionary, and implement IEqualityComparer<Foo>, then pass that into the dictionary constructor.

    Usually it's reasonably clear how to compare keys for a specific situation.