RAD Studio (Common)
ContentsIndex
PreviousUpNext
Class Variable in Generics

The class variable defined in a generic type is instantiated in each instantiated type identified by the type parameters. 

The following code shows that TFoo<Integer>.FCount and TFoo<String>.FCount are instantiated only once, and these are two different variables.

{$APPTYPE CONSOLE}
type
  TFoo<T> = class
    class var FCount: Integer;
    constructor Create;
  end;
  constructor TFoo<T>.Create;
begin
  inherited Create;
  Inc(FCount);
end;

procedure Test;
  FI: TFoo<Integer>;
begin
  FI := TFoo<Integer>.Create;
  FI.Free;
end;

var
  FI: TFoo<Integer>;
  FS: TFoo<String>;

begin
  FI := TFoo<Integer>.Create;
  FI.Free;
  FS := TFoo<String>.Create;
  FS.Free;
  Test;
  WriteLn(TFoo<Integer>.FCount); // outputs 2
  WriteLn(TFoo<String>.FCount);  // outputs 1
end;
Copyright(C) 2009 Embarcadero Technologies, Inc. All Rights Reserved.
What do you think about this topic? Send feedback!