0

In the first version of the implementation in Jon Skeet implementation here, he has the following code:

// Bad code! Do not use!
public sealed class Singleton
{
    private static Singleton instance = null;

    private Singleton()
    {
    }

    public static Singleton Instance
    {
        get
        {
            if (instance == null)
            {
                instance = new Singleton();
            }
            return instance;
        }
    }
}

I'm wondering why not just make it:

public sealed class Singleton
{
  private Singleton() {}
  public static Singleton Instance = new Singleton();
}

What are the differences between the two snippets ?

(I'm aware that using Lazy<T> is much better solution)

Youssef13
  • 3,836
  • 3
  • 24
  • 41

2 Answers2

4

The second example could be set via external code:

Singleton.Instance = null;

The first could not, because it doesn't have a public setter.

The other difference is that the property enables lazy initialisation i.e. the Singleton is only instantited when the property is first accessed, whereas the static field would cause the instance to be created as soon as the program starts running.

Johnathan Barclay
  • 18,599
  • 1
  • 22
  • 35
  • REALLY great point. I thought it can't be set because it needs to set to object of type `Singleton` which has no public constructor. But forgot about setting to `null`. – Youssef13 Jan 19 '20 at 19:58
  • I guess, this should be "The _first_ could not, because it doesn't have a public setter." – Pavel Anikhouski Jan 19 '20 at 20:18
  • But just adding `readonly` behind static would solve this problem. And it would save to test `instance != null`on each access. But Fields are a No-Go for some people. – Holger Jan 19 '20 at 21:40
  • @holger yes true. The other difference would be that the property would enable lazy initialisation. – Johnathan Barclay Jan 19 '20 at 22:09
1

The idea of Singleton is to prevent the ability to instantiate a class more than once (or to avoid having multiple instances of the singelton), and if you use the second snippet other classes will always have the ability to set the singleton class' instance again:

Singleton.Instance = new Singleton(); 

UPDATE:

I didn't notice that the constructor is private then we cannot set it this way. Anyway as @JohnathanBarclay has mentioned in his answer that the class can be reset to null and you will never be able to set it again.

Abdullah Dibas
  • 1,499
  • 1
  • 9
  • 13