Hello,
I am still fairly new to CSharp and am trying to implement a singleton
pattern. I found Jon Skeet's excellent page
(http://www.yoda.arachsys.com/csharp/singleton.html), but am struggling a
little to understand it.
The 4th example seems to be the preferred:
public sealed class Singleton
{
static readonly Singleton instance=new Singleton();
// Explicit static constructor to tell C# compiler
// not to mark type as beforefieldinit
static Singleton()
{
// this is a private static constructor right?
}
Singleton()
{
// this is a private instance constructor?
}
public static Singleton GetInstance()
{
return instance;
}
}
OK, so if I create a new instance of singleton, like this:
Singleton MyInstance = new Singleton;
there is no public constructor, so nothing will happen?
But if I call Singleton.GetInstance, a new incidence of singleton will be
created (if required ) and returned due to the readonly variable? Could I
declare instance as public static readonly and get rid of GetInstance?
I understand from the body of that page that the private static
constructor is necessary to make the beforefieldinit bookkeeping work
out, but why is the other constructor necessary, since they are both
private? Would there be a scenario, where different code would be
required in either?
Thanks for any illumination.
Marc Pelletier