Skip to content
  • Home
  • About
  • No Access
  • Privacy Policy
Bits of .NET
Bits of .NET
  • C#
  • Asp.Net Core
  • SQL
  • Windows
  • WordPress
  • AI
  • JavaScript
  • CSS
  • MORE
    • HTML
    • Ajax
    • Git
    • Docker
    • Kubernetes
    • Photoshop
    • Visual Studio

Bits of .NET

Daily micro-tips for C#, SQL, performance, and scalable backend engineering.

  • C#
  • Asp.Net Core
  • SQL
  • Windows
  • WordPress
  • AI
  • JavaScript
  • CSS
  • MORE
    • HTML
    • Ajax
    • Git
    • Docker
    • Kubernetes
    • Photoshop
    • Visual Studio
C#

C#: Why a Static Constructor Runs at a Time You Didn’t Expect

- 06.09.26 - ErcanOPAK

🔧 Your Static Constructor Isn’t Running When You Think It Is

A static constructor looks like it should run once, at program start, the way a regular constructor runs when you say `new` – but the runtime actually defers it until just before the type is first touched, which means the timing (and the exceptions it can throw) depends on code you may not control.

🔎 The Problem

public static class Config
{
    public static readonly string ConnectionString;

    static Config()
    {
        Console.WriteLine("Loading config...");
        ConnectionString = File.ReadAllText("connstring.txt");
    }
}

// "Loading config..." doesn't print at app startup -
// it prints the FIRST time any member of Config is accessed,
// which could be seconds or minutes into the program's life.
Console.WriteLine("App started");
var cs = Config.ConnectionString;   // <- static ctor actually runs HERE

✅ Why the Timing Is Lazy by Design

  • The CLR guarantees a type’s static constructor runs exactly once, and no later than the first access to any static member or the first instance created – but it does NOT guarantee it runs at process start, so ‘before main()’ is not a safe assumption.
  • This laziness is usually a performance feature – types you never touch never pay their static initialization cost – but it becomes a surprise the first time a rarely-used type’s static constructor throws deep inside a request instead of at startup.

🚨 The Exception Trap: TypeInitializationException

  • If a static constructor throws, .NET wraps it in a `TypeInitializationException` – and marks the type as permanently unusable for the rest of the process; every future access throws the SAME wrapped exception again, even if the underlying problem (a missing file, a bad config value) gets fixed at runtime.
  • This means a transient failure the first time `Config` is touched (file locked for a moment) can look like it ‘never recovers’ even after the lock clears, because the CLR cached the failure against the type itself.

⚠️ How to Get Predictable Timing

  • If you need initialization to happen at a known point (e.g., right after Main starts, or inside a DI container’s startup phase), do it explicitly in a method you call yourself – don’t rely on the static constructor as a startup hook.
  • Touching the type intentionally early (e.g., `RuntimeHelpers.RunClassConstructor`) is possible but rarely worth the complexity – restructuring so initialization isn’t implicit is usually the better fix.

A static constructor doesn’t run when the program starts – it runs when you first ask the type for something, which is a very different promise.

— C# Best Practice

Related posts:

C# — Memory Works with Async, Span Does Not

C# — Memory Works with Async, Span Does Not

C#: Fix a CancellationTokenSource Leak Because CancelAfter Keeps Its Internal Timer Alive Even After...

C#: Fix a CancellationTokenSource Leak Because CancelAfter Keeps Its Internal Timer Alive Even After...

C# DTO Mapping Speed Issues — The Hidden Cost of Reflection in AutoMapper

C# DTO Mapping Speed Issues — The Hidden Cost of Reflection in AutoMapper

Views: 11
Found this useful? Share it
XLinkedInWhatsApp

Post navigation

Windows 11: Fix a Webcam That Shows a Black Screen in Every App but Not in Camera Settings
ASP.NET Core: Fix a Rate Limiter That Blocks Legitimate Traffic Behind a Shared Proxy IP

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

Most Read

  1. 01How to make theater mode the default for Youtube 1,079 views
  2. 02How to add default value for Entity Framework migrations for DateTime and Bool 997 views
  3. 03Get the User Name and Domain Name from an Email Address in SQL 996 views
  4. 04Get the First and Last Word from a String or Sentence in SQL 873 views
  5. 05How to select distinct rows in a datatable in C# 868 views
  6. 06How to enable, disable and check if Service Broker is enabled on a database in SQL Server 671 views
  7. 07Add Constraint to SQL Table to ensure email contains @ 631 views
  8. 08Average of all values in a column that are not zero in SQL 584 views
  9. 09How to use Map Mode for Vertical Scroll Mode in Visual Studio 561 views
Bits of .NET

Daily micro-tips for C#, SQL, performance, and scalable backend engineering.

Social

  • ErcanOPAK.com
  • GoodReads
  • LetterBoxD
  • Linkedin
  • The Blog
  • Twitter
Back to top
© 2026 Bits of .NET | Built with Xblog Plus free WordPress theme by wpthemespace.com