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
property Area: Double read GetArea;names a read-only property with no field behind it.Result := Pi * Radius * RadiusinsideTCircle.GetAreacomputes the value on every read.Ring.Areain the output line reads like a field but runs the getter, so it needs no parentheses.
Keywords and builtins used here
DoubleFormatGetAreaPiResultTCircleWriteLnbeginclassendfunctionprogrampropertytypeusesvar
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.
Step 2 of 3 in Classes, step 20 of 27 in Language basics.