C# Singleton class is the class that allow only one of its object across the program execution. Singleton class is just a concept and in C# programming any class can be designed as singleton class which is supposed to have only one object of it.
Below are the steps to design a class as a singleton class in C# programming with program example.
Step -1: First we need to make a constructor of the class private so that object of the class cannot be created outside of the class.
Step -2: Class will have a static method for example static GetInstance() that will be responsible to create object of its own and return to the client program. This method will be static as client cannot create object so client can call using class name only.
Step -3: Design singleton class GetInstance() method so it can return only one object on multiple calls.
Singleton class example in C#
This is the complete program for design pattern singleton class in C#. This program has comments and validation of the singleton class objects if they have same address is written.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace SingletonDesignPattern
{
//Singleton class that returns only one object.
public class SingleInstanceClass
{
//Create a static variable as static method GetInstance() will
//accept only static variable.
private static SingleInstanceClass instance = null;
//Make the constructor private to stop object
//creation from out side of the class
private SingleInstanceClass()
{
}
//Design GetInstance() method to return only
//one object on multiple calls
//@return : Return type is of same class i.e.SingleInstanceClass
public static SingleInstanceClass GetInstance()
{
//If instance is null then create object of the class
// and return it or else return the same object.
if (instance == null)
{
instance = new SingleInstanceClass();
}
return instance;
}
public void Display()
{
Console.WriteLine("Single Ton Class Function");
}
}
//CLIENT CODE
class Program
{
static void Main(string[] args)
{
//Create 2 objects of the singleton class
SingleInstanceClass obj1 = SingleInstanceClass.GetInstance();
obj1.Display();
SingleInstanceClass obj2 = SingleInstanceClass.GetInstance();
obj2.Display();
//Validate if the address of obj1 and obj2 are same.
//If object.ReferenceEquals() returns true objects are same
//or else different.
//In class is return same object again and again
//It will print same objects.
if (object.ReferenceEquals(obj1, obj2))
{
Console.WriteLine("Same objects");
}
else
{
Console.WriteLine("Different objects");
}
}
}
}
NOTE: Above program source code for C# singleton class is not designed for multi-threaded environment.