Singleton in C#

Singleton in C#

Why read if you can watch?

Watch Singleton's video tutorial
read full article

Ensures a class has only one instance and provide a global point of access to it.

This structural code demonstrates the Singleton pattern which assures only a single instance (the singleton) of the class can be created.

using System;

class MainApp
{

static void Main()
{
// Constructor is protected -- cannot use new
Singleton s1 = Singleton.Instance();
Singleton s2 = Singleton.Instance();

if (s1 == s2)
{
Console.WriteLine("Objects are the same instance");
}

// Wait for user
Console.Read();
}
}

// "Singleton"
class Singleton
{
private static Singleton instance;

// Note: Constructor is 'protected'
protected Singleton()
{
}

public static Singleton Instance()
{
// Use 'Lazy initialization'
if (instance == null)
{
instance = new Singleton();
}

return instance;
}
}
}
Objects are the same instance