1

I've come across a C# behavior that I would like to understand.

Why in both cases instance constructor runs first?

    class Program
    {
        public static void Main()
        {
            //Singleton s = new Singleton(); case 1
            var test = Singleton.Instance; // case 2
        }
    }
    class Singleton
    {
        static readonly Singleton _instance = new Singleton();

        public static Singleton Instance { get { return _instance; } }

        private Singleton()
        {
            Console.WriteLine("Instance Constructor");
        }

        static Singleton()
        {
            Console.WriteLine("Static Constructor");
        }
    }

Output:

Instance Constructor

Static Constructor

Arman Sahakyan
  • 193
  • 2
  • 9
  • Possible duplicate of [Is the order of static class initialization in C# deterministic?](https://stackoverflow.com/questions/3681055/is-the-order-of-static-class-initialization-in-c-sharp-deterministic) – Rotem Apr 28 '18 at 18:58

2 Answers2

6

It doesn't run first, it just looks as if it does. What you wrote is (roughly) equivalent to

class Singleton
{
    static readonly Singleton _instance;

    public static Singleton Instance { get { return _instance; } }

    private Singleton()
    {
        Console.WriteLine("Instance Constructor");
    }

    static Singleton()
    {
        _instance = new Singleton();
        Console.WriteLine("Static Constructor");
    }
}

That is, the instance constructor is called while the static constructor is executing.

The reason field initialisation happens first (before your Console.WriteLine call) in the static constructor is simple: the rest of the static constructor may rely on those fields having been initialised.

0

The constructor creates the object. This action print the first line of words.

private Singleton()
        {
            Console.WriteLine("Instance Constructor");
        }

Then the static instance of your singleton class is called which prints the second line of code.

Tech Labradoodle
  • 667
  • 6
  • 16