I'm trying to understand why this is a correct implementation of the Singleton pattern:
public sealed class Singleton : ISingleton
{
public static Singleton Instance { get; } = new Singleton();
private Singleton() { }
// methods
}
What about the beforefieldinit
flag? According to Jon Skeet article:
The laziness of type initializers is only guaranteed by .NET when the type isn't marked with a special flag called beforefieldinit. Unfortunately, the C# compiler (as provided in the .NET 1.1 runtime, at least) marks all types which don't have a static constructor (i.e. a block which looks like a constructor but is marked static) as beforefieldinit.
Is the static constructor not needed in the newest version of C#?
The code above is the implementation of SystemClock
in NodaTime project, by Jon Skeet.'
EDIT Jon Skeet code for reference (why I'm mentioning this beforefieldinit flag):
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;
}
}
}
Singleton pattern restricts the instantiation of a class and ensures that only one instance of the class exists in the java virtual machine. The singleton class must provide a global access point to get the instance of the class. Singleton pattern is used for logging, drivers objects, caching and thread pool.
One of the commonly used design patterns in C# is the singleton pattern. This design pattern uses a single instance of a class to enable global access to the class members. Instead of having several instances of the same class, singletons have just one instance, and provide convenient access to that single instance.
Both are correct singleton implementations. Whether you need the static constructor just depends on how much you care about full laziness. If you really, really don't want the singleton to be instantiated until it's used by a caller, you should have a static constructor - or use Lazy<T>
. You can use a static constructor in the C# 6 code as well, of course:
public sealed class Singleton : ISingleton
{
public static Singleton Instance { get; } = new Singleton();
static Singleton() { }
private Singleton() { }
// methods
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With