Thursday, November 13, 2008

Implementing Singleton Pattern in C#

Requirement: When class needs to have only one instance, and there should be a global point of access to the instance.
class Singleton
{
private static Singleton instance;

private Singleton() {}

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

Constructor is made private so that the class cannot be instantiated wit
h keyword new
.

To create the object:
Singleton s1 = Singleton.Instance;