Read the syntax
Use static constructors for controlled type initialisation and recognise their failure and ordering limits.
The constructor assigns Count and prints once before the property value is returned.
What it is and why to use it
Some state belongs to a type rather than to each instance, such as a small fixed lookup table. A static constructor initialises that state automatically. It has no parameters or access modifier and cannot be called directly. Avoid placing slow, fallible external operations in type initialisation because every later use can depend on it succeeding.
How it works
For a type with an explicit static constructor, the runtime invokes it at most once during the relevant type initialisation before the triggering use. Static field initialisers also participate in initialisation. Generic closed types maintain separate static state. A static constructor that fails can leave the type unusable and surface TypeInitializationException; it is not an ordinary retry mechanism.
Common mistakes and limitations
Do not block on asynchronous work or acquire complex external dependencies inside a static constructor. Do not infer a complete cross-type initialisation order from one simple example. The runtime’s initialisation guarantees do not make later mutations of static data thread-safe.
Run the examples locally
These complete Program.cs examples use a .NET 10 console project with the C# language version set to 12.0, nullable checking enabled and implicit usings disabled. They use standard .NET libraries and need no extra NuGet packages. This is the verified environment, not a claim that every API requires .NET 10 or works unchanged in .NET Framework, Unity or other runtimes.
Install a supported .NET 10 SDK, create the console project, replace its project file with the settings below, then replace Program.cs with one complete example at a time. Build and run from the project folder. using directives bring namespaces into scope; top-level statements form the program’s entry point, and any helper types follow those statements. Console.WriteLine writes terminal output. Do not combine examples that declare the same type names.
C# in Codectionary’s Playground is editing-only: it does not compile or execute these programs. Run them with the local .NET SDK to reproduce the expected output. Async examples use controlled in-process operations rather than live network services or timing-sensitive delays.
Create and enter a project
dotnet new console -n CSharpExample --framework net10.0
cd CSharpExampleCSharpExample.csproj settings used for these examples
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net10.0</TargetFramework>
<LangVersion>12.0</LangVersion>
<Nullable>enable</Nullable>
<ImplicitUsings>disable</ImplicitUsings>
</PropertyGroup>
</Project>Build and run after saving one example in Program.cs
dotnet build
dotnet run --no-buildContinue learning
Change one input and predict the result before running it. Follow the related guides to connect this topic with the surrounding language features.
Syntax
static Settings() { /* initialise static state */ }Examples
Observe one type initialisation
Access a static property twice and see one setup message.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
Console.WriteLine(Catalog.Count);
Console.WriteLine(Catalog.Count);
static class Catalog {
public static int Count { get; }
static Catalog() {
Console.WriteLine("Initialising catalog");
Count = 3;
}
}
- The first property access triggers the explicit static constructor.
- The constructor assigns Count and prints once before the property value is returned.
- The second access reads the already-initialised state without rerunning setup.
- Expected output: Initialising catalog 3 3
- Keep type initialisation small and dependable.
Keep shared lookup storage private
Build a fixed map once and expose only a query operation.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
Console.WriteLine(Labels.For("php"));
Console.WriteLine(Labels.For("cs"));
static class Labels {
private static readonly Dictionary<string, string> names;
static Labels() {
names = new(StringComparer.Ordinal) { ["php"] = "PHP", ["cs"] = "C#" };
}
public static string For(string id) => names[id];
}
- The static constructor creates a comparer-aware map before the query method uses it.
- The readonly field keeps its reference stable, not its contents automatically immutable.
- This example exposes no mutating operation. Concurrent mutation would need a separate design; static initialisation alone does not protect it.
- Expected output: PHP C#
- Keep type initialisation small and dependable.
Best practices
- Keep type initialisation small and dependable.
- Use an explicit service or suitable lazy design for expensive or retryable work.
Runtime & versions
.NET runtime. Feature availability depends on the language and runtime version used by your project; consult the official reference below.
C# language reference