lundi 13 février 2017

Which is called first static constructor or private constructor

Vote count: 0

I was reading a tutorial for implementing Singleton and the code is

public class Singleton
    {
        private static readonly Singleton instance = new Singleton();

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

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

        public void DoSomething() {
            //this must be thread safe
        }
    }

When I write Singleton.Instance, the output is Private Static

I was expecting it to be Static Private

Reason being that when I read a MSDN tutorial "http://ift.tt/1W6pY2n"

I saw that public constructor was called before the static constructor.

Why is there a difference?

asked 32 secs ago

Let's block ads! (Why?)



Which is called first static constructor or private constructor

Aucun commentaire:

Enregistrer un commentaire