Reputation: 4505
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
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
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
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:
The example code you provided is a textbook example of the Singleton pattern.
Upvotes: 0
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
Reputation: 16618
It is static so every instance of the Singleton type will use the same variable, hence the "singleton" pattern.
Upvotes: 0
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
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