How can Delphi records be initialized automatically?

You can use a hidden string field (which is automatically initialized to an empty string) to implement 'on time' initialization and implicit operators to hide implementation details. The code below shows how to implement a 'double' field which is automatically initialized to Pi.

program Project44;

{$APPTYPE CONSOLE}

{$R *.res}

uses
  System.SysUtils;

type
  TAutoDouble = record
  private
    FValue: double;
    FInitialized: string;
    procedure Initialize(const val: double = Pi);
  public
    class operator Implicit(const rec: TAutoDouble): double;
    class operator Implicit(const val: double): TAutoDouble;
  end;

  TSomeRecord = record
    Value1: TAutoDouble;
    Value2: TAutoDouble;
  end;

{ TAutoDouble }

procedure TAutoDouble.Initialize(const val: double);
begin
  if FInitialized = '' then begin
    FInitialized := '1';
    FValue := val;
  end;
end;

class operator TAutoDouble.Implicit(const rec: TAutoDouble): double;
begin
  rec.Initialize;
  Result := rec.FValue;
end;

class operator TAutoDouble.Implicit(const val: double): TAutoDouble;
begin
  Result.Initialize(val);
end;

var
  sr, sr1: TSomeRecord;

begin
  try
    Writeln(double(sr.Value1));
    Writeln(double(sr.Value2));
    sr.Value1 := 42;
    Writeln(double(sr.Value1));
    sr1 := sr;
    Writeln(double(sr.Value1));
    Writeln(double(sr.Value2));
    Readln;
  except
    on E: Exception do
      Writeln(E.ClassName, ': ', E.Message);
  end;
end.

There's, however, no nice way to make this solution more generic regarding the default value -- if you need a different default value you have to clone TAutoDouble definition/implementation and change the default value.


AFAIK you can't without resorting to tricks that aren't worth it (maybe using interface fields which are guaranteed to be initialized).

Tags:

Delphi