Records

Because of my post about the Switches I would like to mention some things about records. Records are are nice way to do things in an object-oriented way without the overhead of real objects. In the unit System.IOUtils you can find several examples of records.

...
unit System.IOUtils;
...
  TDirectory = record
  public
...

Certainly you have to deal with some disadvantages:

  1. No inheritance. If you need inheritance then use objects.
  2. The constructor needs at least one argument. I guess it is because there is no need to create an instance of a “normal” record.
  3. No destructor. Records are destroyed automatically so that it is not possible to define a destructor.

For the point 1 there is nothing you can do but for the two other pints there is a workaround.

  TRttiContext = record
  ...
  public
    class function Create: TRttiContext; static;
    procedure Free;
    ...
  end;

As you can see it is possible to define a class function for the constructor and a method for Free so so that you can use the record in the way you are used to.

var
  pContext: TRttiContext;
begin
  pContext := TRttiContext.Create;
  try
    ...
  finally
    pContext.Free;
  end;
end;
This entry was posted in Tips and Tricks and tagged . Bookmark the permalink.