0

I need an object through out my application. To achieve this I have two approach

  1. define the object as static.

    public class App
    {
        public static MyClass myObject;
    }
    
  2. Make the class Singleton

    public class MyClass
    {
        private MyClass()
        {
        }
        public static MyClass Instance
        {
            get
            {
                return Nested.instance;
            }
        }
        class Nested
        {
            static Nested()
            {
            }
            internal static readonly MyClass instance = new MyClass();
        }
     }
    

Can anyone help me with advantages and disadvantages of these two approaches.

Daniel Hilgarth
  • 171,043
  • 40
  • 335
  • 443
gmtek
  • 741
  • 3
  • 7
  • 25
  • [Implementing the Singleton Pattern in C#- By Jon Skeet](http://csharpindepth.com/Articles/General/Singleton.aspx) – Habib Jan 31 '13 at 13:03

2 Answers2

2

I don't think either of these approaches are good, and you should investigate inversion-of-control via dependency injection.

Why are the above solutions not good ? They make testing a nightmare, and the lifecycle of the 'global' object is dictated by its consumers. See here for more issues surrounding the singleton anti-pattern.

Instead you're better off creating your object and then injecting it into objects that require it. Injection in this instance simply means providing it via a setter or a constructor argument.

By using injection you configure only the components that require this 'global' component, and by making use of interfaces you can substitute different versions (e.g. real vs. mock variants). Importantly the lifecycle of the 'injected' component is controlled by the surrounding framework, and not the consuming entities.

Community
  • 1
  • 1
Brian Agnew
  • 268,207
  • 37
  • 334
  • 440
  • Didn't understand your suggestion properly? It will be good if you through some more light upon it. – gmtek Feb 01 '13 at 05:12
0

I think the main difference between the 2 options are WHEN the object it will be created. In the case of static member, it will be created when your App object will be created or the first time the class will be used for other static methods/ members.

In the case of singleton, it might not be needed to use it from the beginning, thus initiating it later in time, when the time consumption is not that visible.

GeorgeVremescu
  • 1,253
  • 7
  • 12
  • yes it's true. But what about the lifetime of two objects? Is there any difference? – gmtek Feb 01 '13 at 05:15
  • In both cases the life time of the objects is as long as the garbage collector will allow it. And the garbage collector will not kill the objects until all references to them is gone. And as long as there is the static variable, you have a reference. Basically, the ball is in your court now! – GeorgeVremescu Feb 01 '13 at 07:31