To explain my question I'll use something very similar to the TDictionary
example in Embarcadero's website, but my class implements IComparable
.
In Delphi (XE7):
TCity = class(TInterfacedObject, IComparable)
Country: String;
Latitude: Double;
Longitude: Double;
function CompareTo(Obj: TObject): Integer;
end;
I want a TDictionary
with cities as keys:
Dictionary := TDictionary<TCity, string>.Create;
CityA := TCity.Create;
CityA.Country := 'United Kingdom';
CityA.Latitude := 51.5;
CityA.Longitude := -0.17;
Dictionary.Add(CityA, 'London');
Now, if I create a new city with the same values as before where CityA.CompareTo(CityB)
returns 0
, like:
CityB := TCity.Create;
CityB.Country := 'United Kingdom';
CityB.Latitude := 51.5;
CityB.Longitude := -0.17;
And before adding CityB
to the dictionary, I was expecting that:
Dictionary.ContainsKey(CityB)
would use my CompareTo
implementation and ContainsKey
would return True
, but that is not the case. It seems that my class will also need to inherit from TEqualityComparer
.
So how do I add an equality comparer—used by ContainsKey
—to my class, additional to the CompareTo
already there?
I know I could use a TDelegatedEqualityComparer
and anonymous methods to create a custom comparer to be used when creating the dictionary. Something like:
Dictionary := TDictionary<TCity, string>.Create(CityComparer)
But is there a way to include the equality comparer in TCity
, so that I don't need to have one when creating the dictionary?