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?
Asked
Active
Viewed 8,387 times
10
-
Note that Delphi initializes lifetime-managed types (strings, dynamic arrays, interfaces). – kludg Aug 13 '10 at 14:41
-
5In Delphi-2009 and later a record can be initialized by `Foo := Default(TFoo);`. See [David's answer](http://stackoverflow.com/a/11066205/576719) to the question [How to properly free records that contain various types in Delphi at once?](http://stackoverflow.com/q/11065821/576719). – LU RD Jun 16 '12 at 20:24
-
2also see: [Which variables are initialized when in Delphi?](http://stackoverflow.com/questions/861045/which-variables-are-initialized-when-in-delphi) – Gabriel Jan 27 '17 at 10:46
4 Answers
13
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.

Community
- 1
- 1

Lieven Keersmaekers
- 57,207
- 13
- 112
- 146
-
4Or same code with (probably) better readability: ZeroMemory(@Foo, SizeOf(Foo)); – Im0rtality Aug 13 '10 at 14:34
-
@Im0rtality: I have updated the answer to include your ZeroMemory solution. – Lieven Keersmaekers Aug 13 '10 at 14:47
-
Note that ZeroMemory is a wrapper for FillChar in *some* versions of Delphi (d6 and 7 at least). – Gerry Coll Aug 14 '10 at 03:53
-
You should not use this, when the record contains managed types like strings or interfaces – R. Hoek Apr 26 '22 at 20:03
2
1
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;

Alex
- 11
- 1
1
Since Delphi 2007, you can use the Default()
intrinsic function:
var
LRecord: TMyRecord;
begin
LRecord := Default(TMyRecord);
...

Nat
- 5,414
- 26
- 38