2

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?

Abraham Josef
  • 653
  • 1
  • 8
  • 30

2 Answers2

4

Assuming that the only place where Obj is set is in the static constructor, the first code snippet is correct; the second code snippet is redundant.

Since static constructors run only once per class. If there is no other path to set Obj, its value will always be null at the beginning of the static constructor. Therefore, the check if(Obj==null) will always succeed, which makes it redundant.

Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523
2

The static constructor will only ever be called once, at some point prior to the static variables being allocated.
Which means that your friend is correct, you do not need the if statement - it is redundant.
This is because you cannot call a static constructor manually, it will only be called once, at the start of run-time.

Further reading : https://stackoverflow.com/a/4506997/617485

Community
  • 1
  • 1
Ospho
  • 2,756
  • 5
  • 26
  • 39