More About Records

Since records offer methods and properties they are often used to replace objects. This is possible if there is no need to use inheritance.

But there is a significant difference between both. References to objects are like pointers to a piece of memory whereas records are a piece of memory.

This makes a significant difference if you are using functions that return objects and records. Let’s have a look at one example.

program TestObject;

{$APPTYPE CONSOLE}

{$R *.res}

type
  TMyClass = class(TObject)
  strict private
    FNo: Integer;
  public
    property No: Integer read FNo write FNo;
  end;

  function Clone(const AClass: TMyClass): TMyClass;
  begin
    Result := AClass;
    Result.No := AClass.No + 1;
  end;

var
  pClass: TMyClass;
  pClone: TMyClass;
begin
  pClass := TMyClass.Create;
  try
    pClone := Clone(pClass);
    if pClone.No = pClass.No then
      Writeln('Clone hasn't cloned, it uses the same instance');
  finally
    pClass.Free;
  end;

end.

This is really simply. The clone function returns the reference itself. This means that it doesn’t clone, it uses the same instance!

Now, we will do the same with an record.

program TestRecord;

{$APPTYPE CONSOLE}

{$R *.res}

type
  TMyRecord = record
  strict private
    FNo: Integer;
  public
    property No: Integer read FNo write FNo;
  end;

  function Clone(const ARecord: TMyRecord): TMyRecord;
  begin
    Result := ARecord;
    Result.No := ARecord.No + 1;
  end;

var
  pRecord: TMyRecord;
  pClone: TMyRecord;
begin
  pClone := Clone(pRecord);
  if pClone.No <> pRecord.No then
    Writeln('Clone has really cloned');

end.

Now you can see the differences.

  1. There is no need to create a record, the record is simply there.
  2. With point 1 there is no need to destroy the record.
  3. A function that returns a record automatically creates a new one.
This entry was posted in Tips and Tricks and tagged . Bookmark the permalink.