I was going through the following Singleton implementation mentioned here. I understand static constructors get executed before the first static method call or before te object is instantiated, but did not understand its use here (even from the comments). Could anyone help me understand it?
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;
}
}
}
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'.So, he wants thenew Singleton()to be constructed as late as possible (lazily), and the only way to get the C# compiler to do this is to provide an empty static constructor.