Thursday, 28 September 2017

How to declare Static/Class variables, properties, functions and procedures in Delphi?

In Delphi, we do have static variables, properties, functions and procedures, but instead of the word "static" we refer the word "class". In this tutorial, I have shown the syntax of declaring the static variables, properties, functions and procedures in Delphi. We don't have to use "static" keyword while declaring the static variables and properties, just use "class" keyword. While declaring static functions and procedures, we have to use both "class" and "static" keyword.

Declare a static/class variable in Delphi

type
  TStaticDemoClass = class(TObject)
  public
    class var StaticVar: integer;
  end;
Declare a static/class property in Delphi

type
  TStaticDemoClass = class(TObject)
  private
    class var FStaticVar: integer;
  public
    class property StaticVar: integer read FStaticVar write FStaticVar;
  end;

Now we can use above StaticVar variable/property anywhere in the unit like this:
procedure TForm1.Button1Click(Sender: TObject);
var a:integer;
begin
  TStaticDemoClass.StaticVar := 1;
end;

We can also use static/class functions and procedures in Delphi. Below example, I have copied from documentation:

type
  TMyClass = class
    strict private
      class var FX: Integer;
    strict protected  
      //Note: accessors for class properties must be declared class static.
      class function GetX: Integer; static;
      class procedure SetX(val: Integer); static;
    public
      class property X: Integer read GetX write SetX;
      class procedure StatProc(s: String); static;
  end;

TMyClass.X := 17;
TMyClass.StatProc('Hello');

You need to use "static" keyword after function / procedure declaration. Classes can have static class methods -- i.e. methods that can be called from a class type. Class static methods can be accessed without an object reference. Unlike ordinary class methods, class static methods have no Self parameter at all. They also cannot access any instance members. They still have access to class fields, class properties, and class methods. Also unlike class methods, class static methods cannot be declared virtual.

No comments:

Post a Comment