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
Class Type
Class Instance
Array
Method Reference
Function/Procedure Reference
nil

Class Variables
Class variables are special types of variables that are sometimes referred to as "static" variables. They can be referenced from methods in class instances and from class methods in class types, and are useful for storing data that doesn't change between instances of a class. 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
      ShowMessage(IntToStr(TempInstance.CreateCount));
   finally
      TempInstance.Free;
   end;
end;

The second way is by using a direct class reference:

procedure ShowCreateCount;
begin
   ShowMessage(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