Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I initialize a record declared as a local variable?

Tags:

delphi

I'm using a record composed of strings, booleans, integers, currencies and arrays of other records inside a method of a class. I would like to recursively initialize all fields of a primitive type to empty/false/zero. Delphi doesn't appear to do this by default. Is there a straightforward way to accomplish this that doesn't involve accessing each field by name and setting it manually?

like image 850
Kenneth Cochran Avatar asked Aug 13 '10 14:08

Kenneth Cochran


4 Answers

Since Delphi 2007, you can use the Default() intrinsic function:

var
  LRecord: TMyRecord;
begin
  LRecord := Default(TMyRecord);
  ...
like image 99
Nat Avatar answered Sep 22 '22 04:09

Nat


You can use either one of following constructs (where Foo is a record).

FillChar(Foo, SizeOf(Foo), 0); 

ZeroMemory(@Foo, SizeOf(Foo));

From a post from Allen Bauer

While looking at the most common uses for FillChar in order to determine whether most folks use FillChar to actually fill memory with character data or just use it to initialize memory with some given byte value, we found that it was the latter case that dominated its use rather than the former. With that we decided to keep FillChar byte-centric.

like image 29
Lieven Keersmaekers Avatar answered Sep 22 '22 04:09

Lieven Keersmaekers


well, you may apply a simple legal trick

unit unit1;

interface

type
  PMyRecord = ^TMyRecord;
  TMyRecord = record
    Value: Integer;
    function Self: PMyRecord;
  end;

implementation

function TMyRecord.Self: PMyRecord;
begin
  Result := @Self;
end;

procedure Test(AValue: Integer);
const MyRecord: TMyRecord = (Value: 0);
begin
  MyRecord.Self.Value := AValue;
end;
like image 24
Alex Avatar answered Sep 22 '22 04:09

Alex


Note, that you should use Finalize before FillChar or ZeroMemory in some cases.

like image 37
Alex Avatar answered Sep 20 '22 04:09

Alex