Singleton Class in C#


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

Updated on: 22-Jun-2020

3K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements