3
votes

In singleton pattern, we have a private constructor and a public static method like below -

public class MyClass
{
     private static MyClass _uniqueInstance;

     private MyClass()
     { 
     }

     public static MyClass GetInstance()
     {
         if(_uniqueInstance==null)
         { 
             _uniqueInstance = new MyClass();
         }
         return _uniqueInstance;
     }
}

And we can create ONE and Only ONE instance of this Class by invoking the static method whenever we need the object of this class like -

var myObject = MyClass.GetInstance();

But I am confused why we check for null in the GetInstance() method as the "_uniqueInstance" is already a static variable, so it will be initailized and allocated memory only once . Even if we do not check for null and still initialize the object with "new", memory will not be allocated again for this object as it is a static variable. So, what is the use of this null check ? Please clear my doubt.

4
The point of the check is to make code trickier to understand and introduce problems in multi-threaded environment. See Jon Skeet article - csharpindepth.com/Articles/General/Singleton.aspx - Alexei Levenkov

4 Answers

4
votes

I sense confusion between initializers, factories, and singletons.

A field initializer:

static readonly object Value = new object();

A factory method:

static object CreateValue()
{
    return new object();
}

A singleton pattern:

static object _value;

static object Value
{
    get
    {
        return _value ?? (_value = new object());
    }
}

Initializers are removed to the static constructor upon compilation, which runs once like you guessed. Except for order, the initialization of static fields is uncontrollable. When any static field initializes, then all static fields initialize. A singleton pattern prevents this.

The factory method is intended as an abstraction of an instance constructor.

A singleton pattern can be considered an abstraction of a field initializer, assuring that a resource is not introduced until necessary. However, for resources which are most certainly referenced, like String.Empty, it is wiser to use a static field instead to avoid clutter.

3
votes

If you use the following code:

public static MyClass GetInstance()
{
    _uniqueInstance = new MyClass();
    return _uniqueInstance;
}

then every time someone calls this GetInstance you will get a different instance of the class which contradicts with what a Singleton is. The idea of the Singleton pattern is to always get the same instance of the class, no matter how many times you call it in your application. And this instance should be constructed only once.

So basically the null check will return true only the first time GetInstance is called in order to instantiate the private static field (which is null by default) and on subsequent calls the same instance will be returned.

Bare in mind though that this singleton pattern implementation that you have shown here is not thread safe. If 2 threads call the GetInstance method at the beginning at the same time, potentially they could get 2 different instances.

You can read more about the Singleton pattern and the various C# implementations in this article.

1
votes

We use Singleton pattern to get only one instance of an object and use this instance everywhere.

If we remove the null checking if(_uniqueInstance==null) then every time GetInstance is called a new instance will be created and it will be stored in _uniqueInstance variable.

Even if we do not check for null and still initialize the object with "new", memory will not be allocated again for this object as it is a static variable.

Memory is allocated to _uniqueInstance as a reference type just once because it is static. but you can assign many references to this static variable and those objects can be created as many time as needed in the memory.

So, what is the use of this null check

The null check ensures that _uniqueInstance is assigned just once with an instance of MyClass and it is never changed trough the life time of application domain. So every one call GetInstance will get the same instance of MyClass.

Read more about singleton

0
votes

This is wrong:

Even if we do not check for null and still initialize the object with "new", memory will not be allocated again for this object as it is a static variable.

Calling new will allocate new memory and _uniqueInstance will have a new pointer. So, you'll have different instance on every call of the method - it's not a singleton.