I searched for this a lot, but none of the answers are clear (at-least for me!). Now I'm putting this question in SO, as I believe I can't get a more clarified answer anywhere else.
When should I use a private/static constructor in my class?
I'm fed up of usual answers, so please help me with some real-time examples and advantages/disadvantages of using these constructors.
Static constructors: used for initialising static members.
Private constructors: used when you only want a class to be instantiated from within its own code (typically in a static method). For example:
When you want a constructor, but don't want to expose it to the world. This could be because you have a factory method that calls the constructor (after validation), or because that constructor is called by ctor-chaining (i.e.
public Foo(string) : this() { ...}
).Additionally, note that reflection code is often able to use a private constructor - for example serialization or ORM libraries.
Also, in early C# compilers, when you are writing what would now be a
static
class - having a private constructor was the only way of making it appear uncreatable.When you need to initialize some static state prior to that state being accessed by instances or static methods.
Static constructor is used to intialize the static members of the class and is called when the first instance of the class is created or a static member is accessed for the first time.
Private constructor is used if you have overloads of the constructor, and some of them should only be used by the other constructors