Author: Pieter Valentijn
Making properties in your objects and using the accesors to do something.
Answer:
Property accessors are great. They give you the power to do stuff like initialize
an object or produce data that are dependent on the object's other properties.
You can make properties by declaring them in your interface section and then
pressing Ctrl+Shift+'c' it wil make a private variable called Fsomeproperty and a
set methode called SetSomeProperty.
In this example i made an object that has a property that holds an other object and
on the Read of this property i'll check whether it's not nil so i can create it on
runtime.
You can also check if a value is within it's bounds on the Property's Set Accessor
1 type2 TMySubObject = class3 4 end;
5 6 TMyObject = class7 private8 fMySubObject: TMySubObject;
9 FASecondNum: Integer;
10 FAFirstnum: Integer;
11 function getMySubObject: TMySubObject;
12 function GetTotaalOfFirstAndSecondNum: integer;
13 procedure SetFirstnum(const Value: Integer);
14 public15 16 property MySubObject: TMySubObject read getMySubObject;
17 property AFirstnum: Integer read FAFirstnum write SetFirstnum;
18 property ASecondNum: Integer read FASecondNum write FAFirstnum;
19 property TotaalOfFirstAndSecondNum: integer read20 GetTotaalOfFirstAndSecondNum;
21 end;
22 23 implementation24 25 {$R *.DFM}26 27 { TMyObject }28 29 function TMyObject.getMySubObject: TMySubObject;
30 begin31 // i check here to see if its assigned32 ifnot Assigned(fMySubObject) then33 fMySubObject := TMySubObject.Create;
34 Result := fMySubObject;
35 end;
36 37 function TMyObject.GetTotaalOfFirstAndSecondNum: integer;
38 begin39 Result := FAFirstnum + FASecondNum;
40 end;
41 42 procedure TMyObject.SetFirstnum(const Value: Integer);
43 begin44 // here on the set u can check bounds :) .45 if (Value > 0) and (Value < 1000) then46 FAFirstnum := Value
47 else48 raise Exception.Create('Number out of bounds');
49 end;