Jon Skeet suggests in his singleton implementation that if you require the maximum laziness for your singleton you should add a static constructor which will make the compiler mark the type as beforefieldinit.
However, I did some testing and it seems that it's more lazy without the beforefieldinit.
Code sample (the private constructor call outputs to console and verifies that the fields were initialized:
public sealed class Singleton
{
private static readonly Singleton instance = new Singleton();
public static string Stub()
{
return "123";
}
// Explicit static constructor to tell C# compiler
// not to mark type as beforefieldinit
//static Singleton()
//{
//}
private Singleton()
{
Console.WriteLine("private ctor");
}
public static Singleton Instance
{
get
{
return instance;
}
}
}
When I call Singleton.Stub() the private constructor is not being hit, and when I uncomment the static constructor, the private constructor is always called.
This is the only difference I could track made by the static constructor.
In my attempts to understand what difference will the beforefieldinit do I've also read Skeet's answer in this post tried it with passing false to DoSomething() - with or without the static constructor the private constructor is not being called.
public static void DoSomething(bool which)
{
if (which)
{
var a = Singleton.Stub();
}
else
{
Faketon.Stub();
}
}