Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can Delphi records be initialized automatically?

Tags:

delphi

To initialize Delphi records I've always added a method (class or object) that would initialize to known good defaults. Delphi also allows for defining record "constructors" with parameters, but you cannot define your own parameter-less "constructor".

TSomeRecord = record
 Value1: double;
 Value2: double;

 procedure Init;
end;

procedure TSomeRecord.Init;
begin
  Value1 := MaxDouble;
  Value2 := Pi;
end; 

Given the record above there is no warning that a record has not been initialized. Developers may neglect to call Init on the record. Is there a way to automatically initialize records to my default, potentially more than just a simple FillChar;

For instance

var 
  LSomeRecord: TSomeRecord
begin
  // someone forgot to call LSomeRecord.Init here
  FunctionThatTakesDefaultSomeRecord(LSomeRecord);
end; 

How can a record be initialized to my defaults automatically?

[Note] I don't want to modify the problem after it has been answered. Any readers are directed to read the comments on best practices on using class methods for initialization instead of a mutating object method.

like image 366
Jasper Schellingerhout Avatar asked Sep 08 '16 13:09

Jasper Schellingerhout


1 Answers

Since Delphi 10.4, there are Custom Managed Records

  TMyRecord = record
    Value: Integer;
    class operator Initialize (out Dest: TMyRecord);
    class operator Finalize (var Dest: TMyRecord);
  end;

The huge difference between this construction and what was previously available for records is the automatic invocation.

like image 102
emno Avatar answered Oct 16 '22 15:10

emno