typestar

Properties and getters in Delphi

A circle whose area is a property backed by a getter instead of stored data.

program PropertiesGetters;
uses SysUtils;
type
  TCircle = class
    Radius: Double;                      // the storage
    function GetArea: Double;            // the getter
    property Area: Double read GetArea;  // read-only, computed on access
  end;
function TCircle.GetArea: Double;
begin
  Result := Pi * Radius * Radius;  // Result carries the return value
end;
var Ring: TCircle;
begin
  Ring := TCircle.Create;
  Ring.Radius := 2.5;
  // A property reads like a field, so the getter needs no parentheses.
  WriteLn(Format('r %.1f has area %.2f', [Ring.Radius, Ring.Area]));
  Ring.Free;
end.

How it works

  1. property Area: Double read GetArea; names a read-only property with no field behind it.
  2. Result := Pi * Radius * Radius inside TCircle.GetArea computes the value on every read.
  3. Ring.Area in the output line reads like a field but runs the getter, so it needs no parentheses.

Keywords and builtins used here

The run, in numbers

Lines
20
Characters to type
575
Tokens
96
Three-star pace
70 tpm

At the three-star pace of 70 tokens a minute, this run takes about 82 seconds.

Type this snippet

Step 2 of 3 in Classes, step 20 of 27 in Language basics.

← Previous Next →