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;
}
}
}
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
}
See more on this question at Stackoverflow