What is a Singleton and when should I use it?
-
3Possible duplicate: http://stackoverflow.com/questions/246710/how-to-implement-a-singleton-in-c – Mark Seemann Jan 28 '10 at 15:41
-
4Also, the Singleton is one of the most widely used and abused design patterns in OO programming. – ChaosPandion Jan 28 '10 at 15:46
-
3@Fabiano: Because it has a way of creating couplings that make no sense (how can I get `X` to talk to `Y`? Just make `Y` a singleton!), which in turn leads to difficulties testing/debugging and a procedural style of programming. Sometimes Singletons are necessary; most of the time, not. – Aaronaught Jan 28 '10 at 16:05
-
3This is one of my standard phone interview questions. The correct answer is: never. – jonnii Jan 28 '10 at 16:41
-
Wikipedia link: http://en.wikipedia.org/wiki/Singleton_pattern – Jo Smo Jul 05 '14 at 14:03
-
3@jonnii that's good, it helps warn prospective developers what there boss is like! – Mr. Boy Jul 27 '16 at 15:24
15 Answers
A singleton is a class which only allows one instance of itself to be created - and gives simple, easy access to said instance. The singleton premise is a pattern across software development.
There is a C# implementation "Implementing the Singleton Pattern in C#" covering most of what you need to know - including some good advice regarding thread safety.
To be honest, It's very rare that you need to implement a singleton - in my opinion it should be one of those things you should be aware of, even if it's not used too often.

- 8,548
- 6
- 47
- 55

- 8,156
- 1
- 33
- 43
-
2
-
3Here's a more direct link to what I consider to be the ideal implementation in 2020. That is, "[using .NET 4's Lazy
type](https://csharpindepth.com/Articles/Singleton#lazy)," as well as the link to the Microsoft Doc for the [`Lazy – Chiramisu Feb 20 '20 at 21:55Class`](https://learn.microsoft.com/en-us/dotnet/api/system.lazy-1).
You asked for C#. Trivial example:
public class Singleton
{
private Singleton()
{
// Prevent outside instantiation
}
private static readonly Singleton _singleton = new Singleton();
public static Singleton GetSingleton()
{
return _singleton;
}
}

- 6,924
- 5
- 31
- 47
-
16not thread safe.two thread can call same time and can create two seperate objects. – Alagesan Palani Apr 06 '15 at 07:07
-
5@Alagesan Palani, indeed you are right. I'm not proficient in the low-level details of class-level initialization, but I think the change I made addresses the thread-safe concern. – Chris Simmons Apr 06 '15 at 16:52
-
3sure, i am NOT pointing you are wrong. i am giving a hint to the reader about thread-safety, so that they would be careful if they have to deal with it. – Alagesan Palani Apr 06 '15 at 17:18
-
9No, I think your comment is important. Given that a singleton is supposed to deliver one--and only one--instance, the race condition here opens the possibility that more than one is delivered. See the version now, with static field initialization. I believe this fixes the thread-safety problem, if I read [the docs](https://msdn.microsoft.com/en-us/library/aa645758%28v=vs.71%29.aspx) and [this SO answer](http://stackoverflow.com/a/12159883/208990) correctly. – Chris Simmons Apr 06 '15 at 18:33
-
It's still not thread-safe. Changing the field to static doesn't make it thread-safe. You need to add a constructor that is static and then it will be thread-safe. – Moshe Jun 10 '20 at 13:04
-
1@Moshe, I don't believe a static constructor is needed to ensure thread-safety. According to [MSDN](https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/classes-and-structs/static-classes-and-static-class-members), "Static members are initialized before the static member is accessed for the first time and before the static constructor, if there is one, is called." – Chris Simmons Jun 16 '20 at 21:25
-
This is not thread safe as two different threads can create two objects of the same. Singleton class – Son of Man Jun 20 '23 at 03:39
What it is: A class for which there is just one, persistent instance across the lifetime of an application. See Singleton Pattern.
When you should use it: As little as possible. Only when you are absolutely certain that you need it. I'm reluctant to say "never", but there is usually a better alternative, such as Dependency Injection or simply a static class.

- 2,101
- 14
- 14

- 120,909
- 25
- 266
- 342
-
19I'm not sure that a static class is a better alternative than a singleton... it really depends on the situation and language. – marcgg Jan 28 '10 at 15:43
-
@marcgg, it is not *always* a better alternative, but I have seen singleton implementations with no private data or state, which means that they would have been better off as static classes. – Aaronaught Jan 28 '10 at 15:45
-
9Static classes don't behave in the same way as a singleton, a singleton can be passed into methods as a parameter whereas a static class can not. – TabbyCool Jan 28 '10 at 15:48
-
An example of a singleton being better would be a lazy loaded class, or one where initialization depended on another portion of the program. But unless you need control over the exact time of initialization, a static class handles most of the difficulties, such as synchronization, for you. – Guvante Jan 28 '10 at 15:49
-
4Aggree with marcgg - I don't see a static class as a good alternative to singletons, because you still have the problem of supplying a substitute, e.g. during testing of a component that depends on this class. But I also see different uses, a static class would typically be used for independent utility functions that are independent of state, where a singleton is an actual class instance, and it would typically store a state. I completely agree to use DI instead, and then tell your DI container that you want it to only use a single instance of that class. – Pete Jan 28 '10 at 15:50
-
I should start adding a nitpicker's corner à la Chen. Note the words "usually" and "such as" in the second paragraph. ;) @Pete - some people actually use singletons to implement stateless utility functions, this was what I was getting at and advising against. – Aaronaught Jan 28 '10 at 16:01
-
1
-
9I downvoted this answer because it gives me no information on when to use it. "Only when you need it" doesn't really give me any information at all for someone that's new to singletons. – Sergio Tapia Jan 28 '10 at 16:21
-
@John McClane: I fail to see how the answer you accepted gives any more information than that. – Aaronaught Jan 28 '10 at 16:33
-
1@Pete: I am sure this is a dumb question but what is DI? "I completely agree to use DI instead, and then tell your DI container that you want it to only use a single instance of that class." – Christopher B. Adkins Jan 29 '10 at 11:35
-
10@Adkins: DI stands for Dependency Injection, which is when any class dependencies are passed in through (usually) a constructor or public property. DI alone doesn't solve the "distance" problem, but it is usually implemented alongside an Inversion-of-Control (IoC) container that knows how to automatically initialize any dependencies. So if you are creating a Singleton to solve the "X doesn't know how to find/talk to Y" problem, a combination of DI and IoC can solve the same problem with looser coupling. – Aaronaught Jan 29 '10 at 14:22
-
singletons has two main scenario 1- only one instance/object of that class exist 2- and it exist for life time of the application RUN until the termination ... it is live and available everywhere you want. this properties of singleton makes easy to have and access any live and GLOBAL VALUE/DATA or functionality . ***HOWEVER*** since it is live for life of the application it also consume resources specially when its is WEB-SERVICE and carrying DATA which need to be carefully decide otherwise it will eat your MEMORY. another warning is that the certain CONTEXT is EXPOSED across the application. – Rouzbeh Zarandi May 23 '22 at 06:37
another way to implement singleton in c#, i personally prefer this way because you can access the instance of the singeton class as a property instead of a method.
public class Singleton
{
private static Singleton instance;
private Singleton() { }
public static Singleton Instance
{
get
{
if (instance == null)
instance = new Singleton();
return instance;
}
}
//instance methods
}
but well, as far as i know both ways are considered 'right' so it's just a thing of personal flavor.

- 1,638
- 4
- 22
- 33
-
15not thread safe.two thread can call same time and can create two seperate objects. – Alagesan Palani Apr 06 '15 at 07:07
using System;
using System.Collections.Generic;
class MainApp
{
static void Main()
{
LoadBalancer oldbalancer = null;
for (int i = 0; i < 15; i++)
{
LoadBalancer balancerNew = LoadBalancer.GetLoadBalancer();
if (oldbalancer == balancerNew && oldbalancer != null)
{
Console.WriteLine("{0} SameInstance {1}", oldbalancer.Server, balancerNew.Server);
}
oldbalancer = balancerNew;
}
Console.ReadKey();
}
}
class LoadBalancer
{
private static LoadBalancer _instance;
private List<string> _servers = new List<string>();
private Random _random = new Random();
private static object syncLock = new object();
private LoadBalancer()
{
_servers.Add("ServerI");
_servers.Add("ServerII");
_servers.Add("ServerIII");
_servers.Add("ServerIV");
_servers.Add("ServerV");
}
public static LoadBalancer GetLoadBalancer()
{
if (_instance == null)
{
lock (syncLock)
{
if (_instance == null)
{
_instance = new LoadBalancer();
}
}
}
return _instance;
}
public string Server
{
get
{
int r = _random.Next(_servers.Count);
return _servers[r].ToString();
}
}
}
I took code from dofactory.com, nothing so fancy but I find this far good than examples with Foo and Bar additionally book from Judith Bishop on C# 3.0 Design Patterns has example about active application in mac dock.
If you look at code we are actually building new objects on for loop, so that creates new object but reuses instance as a result of which the oldbalancer and newbalancer has same instance, How? its due to static keyword used on function GetLoadBalancer(), despite of having different server value which is random list, static on GetLoadBalancer() belongs to the type itself rather than to a specific object.
Additionally there is double check locking here
if (_instance == null)
{
lock (syncLock)
{
if (_instance == null)
since from MSDN
The lock keyword ensures that one thread does not enter a critical section of code while another thread is in the critical section. If another thread tries to enter a locked code, it will wait, block, until the object is released.
so every-time mutual-exclusion lock is issued, even if it don't need to which is unnecessary so we have null check.
Hopefully it helps in clearing more.
And please comment if I my understanding is directing wrong ways.

- 2,822
- 4
- 31
- 47
A Singleton (and this isn't tied to C#, it's an OO design pattern) is when you want to allow only ONE instance of a class to be created throughout your application. Useages would typically include global resources, although I will say from personal experience, they're very often the source of great pain.

- 102,548
- 21
- 159
- 201
Whilst the there can only ever be one instance of a singleton, it is not the same as a static class. A static class can only contain static methods and can never be instantiated, whereas the instance of a singleton may be used in the same way as any other object.

- 2,829
- 1
- 24
- 36
It's a design pattern and it's not specific to c#. More about it all over the internet and SO, like on this wikipedia article.
In software engineering, the singleton pattern is a design pattern that is used to restrict instantiation of a class to one object. This is useful when exactly one object is needed to coordinate actions across the system. The concept is sometimes generalized to systems that operate more efficiently when only one object exists, or that restrict the instantiation to a certain number of objects (say, five). Some consider it an anti-pattern, judging that it is overused, introduces unnecessary limitations in situations where a sole instance of a class is not actually required, and introduces global state into an application.
You should use it if you want a class that can only be instanciated once.

- 65,020
- 52
- 178
- 231
I use it for lookup data. Load once from DB.
public sealed class APILookup
{
private static readonly APILookup _instance = new APILookup();
private Dictionary<string, int> _lookup;
private APILookup()
{
try
{
_lookup = Utility.GetLookup();
}
catch { }
}
static APILookup()
{
}
public static APILookup Instance
{
get
{
return _instance;
}
}
public Dictionary<string, int> GetLookup()
{
return _lookup;
}
}

- 9,569
- 5
- 39
- 44
What is a singleton :
It is a class which only allows one instance of itself to be created, and usually gives simple access to that instance.
When should you use :
It depends on the situation.
Note : please do not use on db connection, for a detailed answer please refer to the answer of @Chad Grant
Here is a simple example of a Singleton
:
public sealed class Singleton
{
private static readonly Singleton instance = new Singleton();
// Explicit static constructor to tell C# compiler
// not to mark type as beforefieldinit
static Singleton()
{
}
private Singleton()
{
}
public static Singleton Instance
{
get
{
return instance;
}
}
}
You can also use Lazy<T>
to create your Singleton
.
See here for a more detailed example using Lazy<T>

- 1,100
- 2
- 13
- 24

- 4,507
- 2
- 23
- 40
Here's what singleton is: http://en.wikipedia.org/wiki/Singleton_pattern
I don't know C#, but it's actually the same thing in all languages, only implementation differs.
You should generally avoid singleton when it's possible, but in some situations it's very convenient.
Sorry for my English ;)

- 6,336
- 4
- 30
- 39
I know it's very late to answer the question but with Auto-Property you can do something like that:
public static Singleton Instance { get; } = new Singleton();
Where Singleton
is you class and can be via, in this case the readonly property Instance
.

- 1,934
- 21
- 25
Thread Safe Singleton without using locks and no lazy instantiation.
This implementation has a static constructor, so it executes only once per Application Domain.
public sealed class Singleton
{
static Singleton(){}
private Singleton(){}
public static Singleton Instance { get; } = new Singleton();
}

- 1,151
- 8
- 14
E.X You can use Singleton for global information that needs to be injected.
In my case, I was keeping the Logged user detail(username, permissions etc.) in Global Static Class. And when I tried to implement the Unit Test, there was no way I could inject dependency into Controller classes. Thus I have changed my Static Class to Singleton pattern.
public class SysManager
{
private static readonly SysManager_instance = new SysManager();
static SysManager() {}
private SysManager(){}
public static SysManager Instance
{
get {return _instance;}
}
}
http://csharpindepth.com/Articles/General/Singleton.aspx#cctor

- 415
- 2
- 10
- 20
Fourth version from Implementing the Singleton Pattern in C#
One shortcut you can take with this implementation (and only this one) is to just make instance a public static readonly variable, and get rid of the property entirely. This makes the basic skeleton code absolutely tiny!
public sealed class Singleton
{
public static readonly Singleton Instance = new Singleton();
static Singleton()
{
}
private Singleton()
{
}
}

- 7,338
- 9
- 60
- 94