 
  Data Structure Data Structure
 Networking Networking
 RDBMS RDBMS
 Operating System Operating System
 Java Java
 MS Excel MS Excel
 iOS iOS
 HTML HTML
 CSS CSS
 Android Android
 Python Python
 C Programming C Programming
 C++ C++
 C# C#
 MongoDB MongoDB
 MySQL MySQL
 Javascript Javascript
 PHP PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
How to implement a Singleton design pattern in C#?
Singleton Pattern belongs to Creational type pattern
Singleton design pattern is used when we need to ensure that only one object of a particular class is Instantiated. That single instance created is responsible to coordinate actions across the application.
As part of the Implementation guidelines we need to ensure that only one instance of the class exists by declaring all constructors of the class to be private. Also, to control the singleton access we need to provide a static property that returns a single instance of the object.
Example
Sealed ensures the class being inherited and object instantiation is restricted in the derived class
Private property initialized with null
ensures that only one instance of the object is created
based on the null condition
Private constructor ensures that object is not instantiated other than with in the class itself
Public method which can be invoked through the singleton instance
public sealed class Singleton {    private static int counter = 0;    private static Singleton instance = null;    public static Singleton GetInstance {       get {          if (instance == null)          instance = new Singleton();          return instance;       }    }    private Singleton() {       counter++;       Console.WriteLine("Counter Value " + counter.ToString());    }    public void PrintDetails(string message) {       Console.WriteLine(message);    } } class Program {    static void Main() {       Singleton fromFacebook = Singleton.GetInstance;       fromFacebook.PrintDetails("From Facebook");       Singleton fromTwitter = Singleton.GetInstance;       fromTwitter.PrintDetails("From Twitter");       Console.ReadLine();    } }  Output
Counter Value 1 From Facebook From Twitter
