5

I've written a class like this:

class Singleton
{
    private Singleton()
    {
        Console.WriteLine("Initialized.");
        Singleton.num++;
    }

    public static uint num;

    private static Singleton instance = new Singleton();

    public static Singleton Instance
    {
        get { return Singleton.instance; }
        private set { }
    }
}

And in my main method, if I wrote like this:

        Console.WriteLine("====================");
        Singleton s = Singleton.Instance;
        Console.WriteLine("====================");
        //Console.WriteLine(Singleton.num);

I got a output like:

====================
Initialized.
====================

But if I uncomment the last line, I'll got a output like this:

Initialized.
====================
====================
1

Why the constructor was inkoved before any process in the second case? And why the last line will effect its previous procedures?

Nick
  • 1,417
  • 1
  • 14
  • 21
Ah Meow
  • 51
  • 1
  • http://stackoverflow.com/questions/3965976/when-do-static-variables-get-initialized-in-c – Matteo Umili Jul 16 '15 at 08:02
  • Note that you don't need to specify a setter on a property - it's perfectly fine to have a property that has only a setter, or only a getter. – Luaan Jul 16 '15 at 08:04
  • Observation: The first output only occurs in debug builds; release builds always call the static constructor at startup before Main() is called. See http://stackoverflow.com/a/12816842/106159 – Matthew Watson Jul 16 '15 at 08:06

0 Answers0