How to Implement Singleton Pattern Using C# (C Sharp)?

Singleton pattern falls under the roof of creational design patterns. You use singleton pattern in your code if you want to create only one instance of a class.

For example, you might prefer to have only one printer spooler or single point of access to your database. In such cases you can use this pattern. But ensure that the instance created has to be globally accessed across all relevant pages in your application. Singleton pattern can be implemented using C# in multiple ways. Few of the most frequent ways are discussed in this article.

Method #1:

One way of implementing singleton pattern is demonstrated below:
public class sampleClass {
private static bool flag = false;
private sampleClass() { }
public static sampleClass createInstance() {
if(flag) {
return null;
}
else {
flag = true;
return new sampleClass();
}
}
}
public class testClass {
public void displayMsg(sampleClass obj){
if(obj == null) {
Console.WriteLine(“An instance of the class is already created”);
}
else {
Console.WriteLine(“ Instance is successfully created”);

}
}
public static void Main() {
sampleClass obj = sampleClass.createInstance();
displayMsg(obj);
sampleClass obj1 = sampleClass.createInstance();
displayMsg(obj1);
}
}

Output of this code will be:

Instance is successfully created
An instance of the class is already created

In this example, sampleClass is your singleton class. In this class, you have made the constructor to be private. Hence you cannot directly create instance of sampleClass using new operator as shown below:

sampleclass obj = new sampleClass();

This statement will end up in compilation error.

In this example, you have a private static Boolean variable called flag which is false by default. If an instance of the class is created, then the flag will be set to true. When you are trying to get an instance next time, the flag value will be checked. Since it is true, only a null value will be sent instead of an instance creation. This logic is framed inside createInstance method. You can create an instance of sampleClass only by using this method.

Method #2:

In the above case, you have mentioned the constructor as private and posted the logic inside a class member method. You can also build the logic inside the constructor as shown in the example below:

public class sampleClass {
static bool flag = false;
public sampleClass() {
if(flag) {
throw new Exception(“Instance of sampleClass is already created”);
}
else {
flag = true;
Console.WriteLine(“Instance of sampleclass is successfully created”);
}
}
}
public class testClass {
public static void Main() {
try {
sampleClass obj = new sampleClass();
sampleClass obj1 = new sampleClass();
}
catch(Exception ex) {
Console.WriteLine(“Exception Occurred:”+ex.Message);
}
}
}

Output of this code will be:
Instance of sampleClass is already created
Exception Occurred: Instance of sampleClass is already created

In this method you have framed the entire logic inside the constructor. In addition, if you are trying to create another instance of the class then an exception will be thrown.

Method #3:

You can use sealed classes to implement singleton pattern as shown below:
sealed class sampleClass {
private static readonly sampleClass obj = new sampleClass();
private sampleClass(){ }
public static sampleClass Obj {
get { return obj; }
}
}

In this example, you have used sealed classes and class property to achieve the logic.

Ensure Global Access to the Instance:

So far you have been concentrating on how to implement singleton pattern in C# application code. But after implementing the pattern, you have to ensure that the class instance thus created is globally accessed across necessary pages in the application. For that, you can create the instance of the class and pass it to all relevant pages and classes as a parameter.

If you don’t know which all pages/classes will access this instance then instead of passing it to all pages, you can create a registry containing all singleton classes of your application and ensure that the registry is accessible from all pages and classes.

| Design Guideline for C# Structs (C Sharp) | Design Patterns – Its Importance and Types | How to Implement Proxy Pattern Using C# (C Sharp)? | How to Implement Singleton Pattern Using C# (C Sharp)? | Illustration of Abstract Classes of C# (C Sharp) with Examples | Illustration of Sealed Classes of C# (C Sharp) with Examples | List of Overloadable Operators in C# (C Sharp) | Usage of [ ] and () Operators in C# (C Sharp) | What is C# (C Sharp) Nested Type? |


“Amazon and the Amazon logo are trademarks of Amazon.com, Inc. or its affiliates.”

| Privacy Policy for www.dotnet-guide.com | Disclosure | Contact |

Copyright - © 2004 - 2024 - All Rights Reserved.