When are static fields initialized in C #?

I wrote 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 have an output like:

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

But if I uncomment the last line, I get the following output:

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

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

+5
source share

All Articles