Singleton Class in C#

CsharpProgrammingServer Side Programming

Singleton Class allow for single allocations and instances of data. It has normal methods and you can call it using an instance.

To prevent multiple instances of the class, the private constructor is used.

Let us see an example −

public class Singleton {
   static Singleton b = null;
   private Singleton() {
      }  
}

The following is another example displaying how to display Singleton class −

Example

 Live Demo

using System;

class Singleton {
   public static readonly Singleton _obj = new Singleton();
     
   public void Display() {
      Console.WriteLine(true);
   }
   Singleton() {}
}

class Demo {
   public static void Main() {
      Singleton._obj.Display();
   }
}

Output

True
raja
Published on 21-Aug-2018 16:04:35
Advertisements