0

In TMyList<T>, a generic list similar to TList<T> but simpler, I am trying to free any objects that may be stored in it if OwnsObjects is true.

I can check if the item is tkClass by using GetTypeKind(T), but that does not get me anywhere because I can't seem to be able to typecast T to TObject to free it.

procedure TMyList<T>.Clear;
var
  Index1: Integer;
begin
  if FOwnsObjects then begin
    Index1 := 0;
    while Index1 < FCount do begin
      case GetTypeKind(FList^[Index1]) of
        tkClass: begin
            if TObject(FList^[Index1]) <> nil then begin
              TObject(FList^[Index1]).Free;
              TObject(FList^[Index1]) := nil;
            end;
          end;
      end;
      Inc(Index1);
    end;
  end;
  {more code..}
end;

Is there no way to do this?

Remy Lebeau
  • 555,201
  • 31
  • 458
  • 770
Adem
  • 265
  • 3
  • 10
  • 1
    You can also use [`TObjectList`](https://docwiki.embarcadero.com/Libraries/en/System.Generics.Collections.TObjectList) – Dalija Prasnikar Aug 26 '21 at 06:31
  • Thank you, Remy. 2 short follow up questuins, if I may: Would this be the correct use FList^[Index1] := Default(T); for FList^[Index1] := nil; The other question is: How do I rewrite this line? if FList^[Index1] = nil then Delete(Index1); It isn't accepting FList^[Index1] = Default(T) – Adem Aug 27 '21 at 05:52
  • Thank you Dalija. But in my use case a generic TMyList will be more useful. Plus, I want to have my own implementation without the bloat taht come TList and derivatives. – Adem Aug 27 '21 at 05:58

0 Answers0