Icon Variables (In Classes)

Variables are declared in a class just like they are declared in a unit or function/procedure. Please see the Variable Declarations topic for more information.

Information As a code convention, variable declarations in classes are normally prefaced with an "F" to distinguish them from other variables and properties. The "F" stands for "Field", but this manual will refer to them as variables and not "fields".

If you don't set a default expression for a variable declaration in a class declaration, then the variable will be automatically initialized to the appropriate value for the type when an instance of the class is created:

TypeInitial Value
String''
Char#0
Integer
Double
0
Enumerated TypeLowest Member Value
BooleanFalse
DateTime0
Object
Array
Method
nil

Class Variables
Class variables are special types of variables that are sometimes referred to as "static" variables. They can be referenced from class instances and also directly from class references where no instance of the class exist, and are useful for storing data that doesn't change between instances of a class. Class variables can only be modified by class methods or class properties. Please see the Methods and Properties topics for more information on class methods and properties.

Class variables are declared by prefacing a variable declaration with the class keyword. For example, the following class declaration includes a class variable that keeps track of how many instances of the class have been created:

TMyClass = class
   private
      class FCreateCount: Integer;
   public
      constructor Create; override;
      class property CreateCount: Integer read FCreateCount;
   end;

implementation

constructor TMyClass.Create;
begin
   inherited Create;
   Inc(FCreateCount);
end;

The CreateCount class property above, and subsequently the FCreateCount class variable, could be accessed in two different ways. The first way is by referring to the CreateCount class property for an instance of the TMyClass class:

procedure ShowCreateCount;
var
   TempInstance: TMyClass;
begin
   TempInstance:=TMyClass.Create;
   try
      window.alert(IntToStr(TempInstance.CreateCount));  // window class is in WebDOM unit
   finally
      TempInstance.Free;
   end;
end;

The second way is by using a direct class reference:

procedure ShowCreateCount;
begin
   window.alert(IntToStr(TMyClass.CreateCount));
end;

The second way is easiest when you don't have an instance of the class available.

One of the most significant benefits of class variables is that only one instance of each class variable ever exists, thus saving memory. They are also very useful for implementing singleton instances of classes and implementing namespaces for code that otherwise would use normal functions and procedures declared outside of a class.
Image