Generics equality and comparing in Delphi

Suppose you have 2 values that are declared as generics, and you want to perform equality, or comparison, how would you do this?

Value1, Value2: V;

You'll need to obtain a generics comparer.

Given the declaration: LComparer: IComparer<V>;

// Here's how you obtain a comparer: LComparer := TComparer<V>.Default; // declared in System.Generics.Defaults;

Then, to compare, here's what you do:

case LComparer.Compare(Value1, Value2) of
 -1: ... Value1 is smaller than Value2
  0: ... Value1 is equal to Value2
  1: ... Value1 is greater than Value2
end;

In cases of LComparer being assigned the result of TComparer<string>.Default, you can get values less than and greater than 0, so you might want to consider another way to compare, like so:

LCompareResult := LComparer.Compare(Value1, Value2);

if LCompareResult < 0 then
   ... else
if LCompareResult = 0 then
   ... else
if LCompareResult > 0 then
  ...

Thanks to fellow MVP, Stefan G who pointed out that for string comparers, you can get results having negative and positive values, not just -1 and +1.

Published Thu, 16 Feb 2017 @ 8:33 PM by chuacw
Related articles: