Singleton Pattern in C#

Singleton Pattern ensures that a class has only one instance and provide 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 Singleton class by calling static method created above. If you compare both objects, they are 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 Singleton class. In the Main Method, assign value to string field for both objects. Now write the value of the string field to console. The string field contains the same value which is assign at last. 
 
Code:

class
Singleton

{

  private static Singleton _instance;

  public string strName;

  protected Singleton()

 {

  }

  public static Singleton Instance()

 {

        if (_instance == null) _instance = new Singleton();

        return _instance;

  }

}

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 ...

Up Next
    Ebook Download
    View all
    Learn
    View all