What are the advantages and when is it appropriate to use a static constructor?
public class MyClass
{
protected MyClass()
{
}
public static MyClass Create()
{
return new MyClass();
}
}
and then creating an instance of the class via
MyClass myClass = MyClass.Create();
as opposed to just having a public constructor and creating objects using
MyClass myClass = new MyClass();
I can see the first approach is useful if the Create method returns an instance of an interface that the class implements…it would force callers create instances of the interface rather than the specific type.
This is the factory pattern, and it could often be used to produce a subclass, but allow the parameters to the static method determine which one.
It could also be used if a new object isn’t always required, for example in a pooling implementation.
It can also be used if all instances of the object needs to be cached or otherwise registered upon creation. This ensures that the client doesn’t forget to do that.
And of course, it is part and parcel of the Singleton pattern.