Please let me know what the best way to implement Singleton Design Pattern in C# with performance constraint?
Asked
Active
Viewed 7,120 times
7
-
1What is the "performance constraint" you speak of? – Oded May 25 '10 at 06:07
-
I would want the fastest implementation. I have heard about an article on this site but do not remember the name. If someone knows, please post it here. – Mark Attwood May 25 '10 at 06:12
2 Answers
7
Paraphrased from C# in Depth: There are various different ways of implementing the singleton pattern in C#, from Not thread-safe to a fully lazily-loaded, thread-safe, simple and highly performant version.
Best version - using .NET 4's Lazy type:
public sealed class Singleton
{
private static readonly Lazy<Singleton> lazy =
new Lazy<Singleton>(() => new Singleton());
public static Singleton Instance { get { return lazy.Value; } }
private Singleton()
{
}
}
It's simple and performs well. It also allows you to check whether or not the instance has been created yet with the IsValueCreated property, if you need that.

Gang
- 418
- 5
- 7
2
public class Singleton
{
static readonly Singleton _instance = new Singleton();
static Singleton() { }
private Singleton() { }
static public Singleton Instance
{
get { return _instance; }
}
}

CARLOS LOTH
- 4,675
- 3
- 38
- 44