tags:

views:

132

answers:

2

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?

+6  A: 

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.

Lieven
Or same code with (probably) better readability: ZeroMemory(@Foo, SizeOf(Foo));
Im0rtality
@Im0rtality: I have updated the answer to include your ZeroMemory solution.
Lieven
Note that ZeroMemory is a wrapper for FillChar in *some* versions of Delphi (d6 and 7 at least).
Gerry