7

There is a class TPerson. It is known that FSecondName unique to each object.

type
  TPerson = class(TObject)
  private
    FAge:        Integer;
    FFirstName:  String;
    FSecondName: String;
  public
    property Age:        Integer read FAge;
    property FirstName:  String  read FFirstName;
    property SecondName: String  read FSecondName;
    constructor Create;
  end;

How can I add a class field (like static field in C#) Persons: TDictionary (String, TPerson), where the key is SecondName and the value is an object of class TPerson.

Thanks!

Andrew
  • 157
  • 2
  • 7
  • 2
    No two people will have the same second name? A wild, progressive society where family names are replaced by GUID? – J... Aug 09 '13 at 12:44

1 Answers1

12

You can declare a class variable:

type 
  TMyClass = class
  private
    class var
      FMyClassVar: Integer;
   end;

Obviously you can use whatever type you like for the class variable.

Class variables have global storage. So there is a single instance of the variable. A Delphi class variable is directly analagous to a C# static field.

David Heffernan
  • 601,492
  • 42
  • 1,072
  • 1,490
  • How do you set the value? Can you do that in the initialization block of that unit? Do you need a `public class procedure SetMyClassVar` for this to work? – Claude Martin Feb 24 '17 at 10:01
  • Initialization block works. As does a class constructor. Look that up in the docs. Different from a normal constructor. – David Heffernan Feb 24 '17 at 10:56