lundi 25 mai 2015

Static Constructor and singleton

My friend told me that the following is one of the ways to create singleton design pattern in C#

    public class class1{

    public static class1 Obj { get; private set; }

    static class1()
    {
        Obj = new class1();
    }
}

He told me that the static constructor runs only one time in application, so only one instance of class1 will be created, but I see that I have to add this if(Obj==null) to check the existence of object

      public class class1{

        public static class1 Obj { get; private set; }

        static class1()
        {
            **if(Obj==null)**
            Obj = new class1();
        }
    }

which code is correct?

Aucun commentaire:

Enregistrer un commentaire