I have some code as shown below. I guess it is Singleton pattern. Why do I need a static constructor. Also what is the advantages of this? Thanks for your reply …
public sealed class Myclass
{
static Myclass()
{
Myclass.Application = new Myclass();
}
protected Myclass()
{
}
static Myclass _application;
public static Myclass Application
{
get { return Myclass._application; }
protected set { Myclass._application = value; }
}
string _name;
public string Name
{
get { return _name}
protected set { _name= value; }
}
}
To start with, this class is somewhat odd for having a protected constructor. It’s not a fatal flaw given that it’s sealed, but it’s distinctly odd.
There’s a potential difference in timing between this code and the nearly-equivalent use of a static variable initializer:
(There’s no need for a setter in this case, of course.)
You can’t do that with an automatically implemented property though.
Using static initialization in some form gets you “free” thread-safety – you don’t need to do any locking in order to get lazy initialization.
You may find my singleton implementation article interesting for more options.