Hello

Hello,

Given : 

Type
  TMyObject = Class(TInterfacedObject, IComparable)
  Public
    Name   : String;
    Value: LongInt;
    Function CompareTo(Obj: TObject): Integer;
  End;
  ...
Function TMyObject.CompareTo(Obj: TObject): Integer;
 Var
  ObjComp: TMyObject;
 Begin
  ObjComp := Obj As TMyObject;
  result := self.Value - obj.Value;
End;


The CompareTo  method is not used when TList.Sort()  is called. A strange sort (binary , I supposed) is done by default.

So what is the IComparable interface for ????? And how do I use my nice CompareTo method ?

Comments

  1. So, IComparable is senseless, if you must pass the comparing method of your object in parameter ....

    ReplyDelete
  2. Probably the same person that copied the IEnumerable and IEnumerator interfaces from C# somewhere around 2009 because it contains the same mistake: generic interface inherits from the non generic one.

    A problem that arises in the Delphi world with having an interface for something like ISerializable or IComparable is the reference counting. In your case this would result in memory leaks if you a TList and then the comparer checks for the IComparable interface on the object. Because then after the Supports (or QueryInterface) call the reference counting is triggered which causes the instance to be destroyed. In C# land there is no problem with mixing object and interface references.

    I should rather have been solved by introducing a virtual CompareTo into TObject like done with the Equals method.

    However I will take a look into this and might implement it for Spring4D.

    Edit: Ok, no guid specified on IComparable which makes it impossible to be used in a generic list.

    ReplyDelete
  3. Stefan Glienke  Thank you very much for this very well documented and argumented answer !!! I used IComparable in C# world,  and I was wondering if my memory was faulty ... So , finally, we can state that IComparable interface is useless , as its main reason of existence can not be used ....

    ReplyDelete

Post a Comment