Static constructor
Context: A static constructor initializes static fields or performs one‑time setup. It is called automatically before the first static member access or first instance creation.
Syntax
Section titled “Syntax”class ClassName{ static ClassName() { // initialization code }}Characteristics
Section titled “Characteristics”- No parameters.
- No access modifiers (implicitly private).
- Cannot be called directly.
- Runs at most once.
Example
Section titled “Example”public class Config{ public static readonly string ConnectionString; static Config() { ConnectionString = LoadFromFile(); } private static string LoadFromFile() => "Server=...";}Order of Execution
Section titled “Order of Execution”- Static constructor runs.
- Then instance constructors (if creating instances).
Exceptions
Section titled “Exceptions”If a static constructor throws an exception, the type becomes unusable.