Class Variable in Generics

From RAD Studio
Jump to: navigation, search

Go Up to Generics Index

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;
 var
   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.

See Also