This question came up when I was going through a similar question for Java. What is an efficient way to implement a singleton pattern in Java?
Can we implement something similar in C#?
This question came up when I was going through a similar question for Java. What is an efficient way to implement a singleton pattern in Java?
Can we implement something similar in C#?
You must have checked Implementing the Singleton Pattern in C# by Jon Skeet
All these implementations share four common characteristics, however:
- A single constructor, which is private and parameterless. This prevents other > >classes from instantiating it (which would be a violation of the pattern). Note that it >also prevents subclassing - if a singleton can be subclassed once, it can be subclassed >twice, and if each of those subclasses can create an instance, the pattern is violated. The factory pattern can be used if you need a single instance of a base type, but the exact type isn't known until runtime.
- The class is sealed. This is unnecessary, strictly speaking, due to the above point, but may help the JIT to optimise things more.
- A static variable which holds a reference to the single created instance, if any.
- A public static means of getting the reference to the single created instance, creating one if necessary.
public class Singleton
{
static readonly Singleton _instance = new Singleton();
static Singleton() { }
private Singleton() { }
public static Singleton Instance
{
get { return _instance; }
}
}
common way to implement one
public sealed class Singleton
{
private static readonly Singleton instance = new Singleton();
private Singleton() {}
static Singleton() {}
public static Singleton Instance { get { return instance; } }
}
public class Singleton
{
private static Singleton instance = null;
public static Singleton Instance
{
get
{
if (instance == null)
{
instance = new Singleton ();
}
return instance;
}
}