4.7 Properties

A global block can declare properties, just as they could be defined in a class. The difference is that the global property does not need a class instance: there is only one instance of this property. Other than that, a global property behaves like a class property. The read/write specifiers for the global property must also be regular procedures, not methods.

The concept of a global property is specific to Free Pascal, and does not exist in Delphi. ObjFPC mode is required to work with properties.

The concept of a global property can be used to “hide” the location of the value, or to calculate the value on the fly, or to check the values which are written to the property.

The declaration is as follows:

_________________________________________________________________________________________________________
Properties

--              -        -------------------              ------
  property-definition  identifier  -              -| property-specifiers
                           property- interface

 --property-interface -|---------------------:-type- identifier-
                  -property- parameter- list--
------------------------------------------------------------------
    index  integer- expression

--property-parameter- list [--|parameter- declaration--] ------------------
                        ---------;---------

--property-specifiers--|-------------|--------------|----------------
                  -read-specifier-- -write- specifier-- -default- specifier-

--read-specifier- read -field- or- function --------------------------------

--           -     -              -------------------------------
  write- specifier write   field- or- procedure

--            ---      ------------------------------------------
  default- specifier |default  -       -| |
                ------nodefcaounltstant---|

--field-or- procedure----field- identifier---------------------------------
                  procedure- identifier

--field-or- function-|--field- identifier-----------------------------------
                -function-identifier--
___________________________________________________________________

The following is an example:

{$mode objfpc}  
unit testprop;  
 
Interface  
 
Function GetMyInt : Integer;  
Procedure SetMyInt(Value : Integer);  
 
Property  
  MyProp : Integer Read GetMyInt Write SetMyInt;  
 
Implementation  
 
Uses sysutils;  
 
Var  
  FMyInt : Integer;  
 
Function GetMyInt : Integer;  
 
begin  
  Result:=FMyInt;  
end;  
 
Procedure SetMyInt(Value : Integer);  
 
begin  
  If ((Value mod 2)=1) then  
    Raise Exception.Create('MyProp can only contain even value');  
  FMyInt:=Value;  
end;  
 
end.

The read/write specifiers must be in the same unit as the unit which declared the property.

More information about properties can be found in chapter 6, page 307.