Singleton Pattern In C#

Introduction

Singleton Pattern ensures that a class has only one instance and provides a global point of access to it.

Sample code

Create a Singleton Class with a private static object of itself. Create a constructor (either private or protected). Create a static method that returns an object of itself (Singleton class).

In Main, create 2 objects of the Singleton class by calling the static method created above. If you compare both objects, they are the same.

In this way, a singleton pattern can be applied so as to create a single instance of a class.

For more clarification, add a public string field in the Singleton class. In the Main Method, assign a value to the string field for both objects. Now write the value of the string field to the console. The string field contains the same value, which is assigned at last.

Example

class Singleton
{
    private static Singleton _instance;
    public string strName;
    protected Singleton()
    {
    }

    public static Singleton Instance()
    {
        if (_instance == null) _instance = new Singleton();
        return _instance;
    }
}
class Program
{
    static void Main(string[] args)
    {
        Singleton s1 = Singleton.Instance();
        Singleton s2 = Singleton.Instance();
        if (s1 == s2)
        {
            Console.WriteLine("Same Object");
        }
        else
        {
            Console.WriteLine("Different Object");
        }
        s1.strName = "Rajul";
        s2.strName = "Aggarwal";
        Console.WriteLine("s1: {0}, s2: {1}", s1.strName, s2.strName);
    }
}

Enjoy Programming.


Similar Articles