Pankaj
Pankaj

Reputation: 4505

Why is instance member static in singleton class?

This is a singleton class

public sealed class Singleton
{
    static Singleton instance=null;
    static readonly object padlock = new object();

    Singleton()
    {
    }

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

my question is static Singleton instance=null; why this is static?

Upvotes: 0

Views: 3349

Answers (8)

Tin Nguyen
Tin Nguyen

Reputation: 315

I think because you used:

public static Singleton Instance()

That function is static, so your instance variable need to be static too.

Upvotes: 0

TomTom
TomTom

Reputation: 62093

Because it if would not be static, it would be a singleton only in name. And i could create thousands of instance of it.

Upvotes: 0

Jagd
Jagd

Reputation: 7307

Succinctly, Singleton is a design pattern used to ensure that only one instance of something is ever created within a given scope.

This pattern is accomplished by a few main concepts:

  1. creating a static instance of some object
  2. creating a private constructor
  3. disallowing the class to be extended by another (sealed)
  4. providing a static method that returns an instance of the static object

The example code you provided is a textbook example of the Singleton pattern.

Upvotes: 0

Tetsujin no Oni
Tetsujin no Oni

Reputation: 7367

The purpose of Singleton is to have only one instance of that object[1]. By making a sealed class with a private static instance which is automatically instantiated on first access, you provide its necessary trait of only creating one copy of the actual object that is then accessed by the Singleton.Instance property elsewhere in the system.

[1] within any AppDomain, anyway.

Upvotes: 1

Louis Kottmann
Louis Kottmann

Reputation: 16618

It is static so every instance of the Singleton type will use the same variable, hence the "singleton" pattern.

Upvotes: 0

vc 74
vc 74

Reputation: 38179

The 'instance' field holds the reference of the one and only instance.

It is stored in a static variable because its scope has to be the class itself and not a particular instance.

Upvotes: 7

John
John

Reputation: 6553

Because you only want one (static) instance ever in the program

Upvotes: 0

Icarus
Icarus

Reputation: 63956

Because you are referencing the variable inside a static Property (Instance) and you can't reference instance variables inside static methods or properties.

The idea of having a Singleton is to only have one and only one instance at all times running.

Upvotes: 5

Related Questions