Class constructor

Top  Previous  Next

What is translated > Types > Records, Classes, Interfaces > Class > Constructors > Class constructor

In Delphi, besides instance constructors, there is a class constructor that runs once per type before the first use of that type, after all involved unit initialization sections. “Use” includes creating an instance, accessing a class member, or querying RTTI. A base type’s class constructor runs before the derived type’s class constructor.

 

A Delphi class constructor is declared as:

 

class constructor Create;

 

C# equivalent: the static constructor

 

C# has a built-in concept of static construction:

 

static MyType()

{

   // one-time initialization per closed type

}

 

 

Semantics (very close to Delphi):
Runs automatically once per type before the first use (first static member access or first instance creation).
It is thread-safe and cannot be called explicitly or have parameters/visibility modifiers.
With inheritance, the base type’s static constructor runs first.
For generics, the static constructor runs once per closed generic type (e.g., Foo<int> and Foo<string> each initialize separately).
If the static constructor throws, subsequent uses observe a TypeInitializationException and the type remains uninitialized until the process/app domain ends.

 

 



This page belongs to the Delphi2C# Documentation

Delphi2C# home  Content