Hey guys

Hey guys,

Is there a equivalent version of System.Array.Clear(Array array, int index, int length) from .NET to Delphi? Is it possible to clear a dynamic array entirely, or a specific range of it? Sorry for any inconvenience.

Thanks in advance.

Comments

  1. With mORMot this is easy!

    type
      TClientDataArray = array of TClientData {this is record};

    var
      I, Count: Integer;
      AClients: TClientDataArray;
      Client: TClientData;
      ClientsA: TDynArray;
    begin
        ClientsA.Init(TypeInfo(TClientDataArray), AClients);
        ClientsA.Clear;
        Client.FirstTime := ClientsLastUpdated;
        ClientsA.Add(Client);
        for I := 0 to Count - 1 do begin
          // set Client data
          ClientsA.Add(Client);
        end;
    end;

    ReplyDelete
  2. FillChar(Array[Start], SizeOf(Array[0]) * NumberOfElements, #0);

    ReplyDelete
  3. Lars Fosdal This will mess up managed types. You will have to call System.Finalize first - but that also depends on how you move around items in the array (if you are using System.Move you can just FillChar. If you move them manually - as you have to do for nextgen and weakrefs - you have to call Finalize)
    That all has already been solved by System.Generics.Collections or Spring4D :)
    Alex Egorov Afair mormot TDynArray does not handle every dynamic array type.

    ReplyDelete
  4. class procedure TMyArray.Clear(var Arr: TArray; start,count: Integer);
    var
      i: Integer;
    begin
      if (start < 0) or (start >= Length(Arr)) or
         (start + count > Length(Arr)) then
        raise EArgumentOutOfRangeException.CreateRes(@SArgumentOutOfRange);
      for i := start to start + count - 1 do
        Arr[i] := Default(T);
    end;

    ReplyDelete
  5. Note: If you are using classes, you may have to free the objects as well.

    ReplyDelete
  6. Finalize(Array[Start], Count);
    FinalizeArray(@Array[Start], TypeOf(ArrayElementType), Count);

    ReplyDelete
  7. Stefan Glienke The way as System.Generics.Collections handles every generic type is a bit ugly IMHO. It is not truly generic :( but it works pretty well.

    ReplyDelete
  8. Horácio Filho Look into the XE7 code, that's not ugly at all.

    ReplyDelete

Post a Comment