A type’s static fields don’t get initialized until the type is referenced

Most of you likely already know this, but I’ve seen 2 customers that were confused by this but I forgot to post this back then.  The idea is that they were avoiding the use of static fields because they had the belief that the static fields in all the types in an assembly were initialized (if they had initializers) when the assembly loaded instead of when the type with the static fields was first referenced.

This makes, for the typical class, a very nice and simple singleton class.  Sure, if the class has things in it (like a public const or something) that you can access and don’t need an instance around, then accessing those things will create the singleton instance sooner than needed, but I avoid putting such things in my singleton classes in the first place, although maybe that’s just me 🙂

Main is running, yay!
Instantiating my singleton
7 + 3 = 10
Main is done running, boo!

using System;

class Program
    static void Main(string[] args)
        Console.WriteLine("Main is running, yay!");
        MySingleton.Instance.Foo = 7;
        MySingleton.Instance.Foo += 3;
        Console.WriteLine("7 + 3 = {0}", MySingleton.Instance.Foo);
        Console.WriteLine("Main is done running, boo!");

public class MySingleton
    private MySingleton()
        Console.WriteLine("Instantiating my singleton");

    private static readonly MySingleton m_instance = new MySingleton();
    public static MySingleton Instance { get { return m_instance; } }

    public int Foo { get; set; }

Skip to main content