Records and Advanced Records

10.1 Basic Records (Value Types)

type
  TPerson = record
    Name: string;
    Age: Integer;
    Email: string;
  end;

var
  P1, P2: TPerson;
begin
  P1.Name := 'Ana';
  P1.Age := 30;
  P2 := P1;               // COPY (value semantics)
  P2.Name := 'Bo';        // P1 unchanged
  P1 := Default(TPerson); // reset to defaults
end;

10.2 Advanced Records (Methods, Properties, Constructors)

Records can't inherit, but they can implement methods, operators (Module 26), and helpers. Record constructors must have parameters (parameterless ones come with custom managed records).

type
  TVector2 = record
  private
    FX, FY: Double;
    function GetLength: Double;
  public
    constructor Create(AX, AY: Double);
    function Add(const Other: TVector2): TVector2;
    function ToString: string;
    property X: Double read FX write FX;
    property Y: Double read FY write FY;
    property Length: Double read GetLength;
    class function Zero: TVector2; static;
  end;

constructor TVector2.Create(AX, AY: Double);
begin
  FX := AX;
  FY := AY;
end;

function TVector2.GetLength: Double;
begin
  Result := Sqrt(FX * FX + FY * FY);
end;

function TVector2.Add(const Other: TVector2): TVector2;
begin
  Result := TVector2.Create(FX + Other.FX, FY + Other.FY);
end;

function TVector2.ToString: string;
begin
  Result := Format('(%.2f, %.2f)', [FX, FY]);
end;

class function TVector2.Zero: TVector2;
begin
  Result := TVector2.Create(0, 0);
end;

var V := TVector2.Create(3, 4);
Writeln(V.Length:0:1, ' ', V.Add(TVector2.Zero).ToString);

10.3 Variant Records and Packed Records

{$ALIGN} / {$A8} directives control alignment. SizeOf(THeader) = 7 because it's packed.

type
  TShapeKind = (skCircle, skRect);
  TShape = record
    Name: string[20];
    case Kind: TShapeKind of         // variant part (overlapping memory)
      skCircle: (Radius: Double);
      skRect: (Width, Height: Double);
  end;

  THeader = packed record            // no alignment padding (file formats, protocols)
    Magic: Cardinal;
    Version: Byte;
    Flags: Word;
  end;

10.4 Records vs Classes

Value (copied) Stack / inline Heap (Create/Free) No (helpers only) Small data, math types, DTOs Objects with identity/behavior