-2

Is there any difference /tradeoff between using a static member object and the singleton pattern? I often use the code below in C#, but are there any use cases where the Singleton is preferred?

 public class MyStaticObject
    {
        static MyStaticObject _object =new MyStaticObject();

        // OR with static constructor
        //static MyStaticObject _object;
        //static MyStaticObject()
        //{
        //    _object = new MyStaticObject();
        //    // additional static construction logic...
        //    //   ...
        //}
    }

NOTE: This is not the same question as: Difference between static class and singleton pattern?

and other questions which look at static CLASSES. Here in my program, the class is not static, it is just a singleton object. So I have all the benefits of inheritance as listed in the question in the link, but I am not using the singleton pattern for construction.

Community
  • 1
  • 1
shelbypereira
  • 2,097
  • 3
  • 27
  • 50
  • The singleton-pattern is usually combined with a readonly-instance which - once set - can´t be changed. With a static member you could change the instance. However there´s no difference in your code as both will go to a static constructor-call. You´re not using a singleton at all. – MakePeaceGreatAgain Dec 21 '16 at 11:30
  • HImBromBeere: Hello, yes I realize I am not using a Singleton, I am using the static constructor or static member in this case, with a singleton I would normally have a static method which checks if instance is null and then create and return it if it is null. However I think I achieve the same result with a static constructor or static member. So de we really need the singleton pattern then? – shelbypereira Dec 21 '16 at 11:39
  • The point is as I already said you can change a static member as often as you want. A singleton however usually references the same instance during the whole lifetime of your app so you can *not* change that reference ( as it is `readonly`). – MakePeaceGreatAgain Dec 21 '16 at 11:46

1 Answers1

0

Singleton pattern says that you will have only one instance of given type. You can achieve it in different ways. You can do it with static classes/members or using IoC container (which better from my point), or some another way.

tym32167
  • 4,741
  • 2
  • 28
  • 32