Search code examples
c#.netstatic-constructorprivate-constructor

Private vs Static constructors in .Net


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.


Solution

  • 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:

    public class Thing
    {
        static int Number;
    
        static Thing()
        {
            Number = 42; // This will only be called once, no matter how many instances of the class are created
        }
    
        // This method is the only means for external code to get a new Thing
        public static Thing GetNewThing()
        {
            return new Thing();
        }
    
        // This constructor can only be called from within the class.
        private Thing()
        {
        }
    }