Execution Order of Constructors in C#

 

 

 

  • Base static constructor: static Base() is called the first time the Base class is accessed (which happens when Derived is loaded, as it inherits from Base). Static constructors run only once per class.
  • Derived static constructor: static Derived() is called the first time the Derived class is accessed (when you try to create an instance of it). Static constructors run only once per class.
  • Base public constructor: public Base() is called because the public constructor of Derived (public Derived() : base()) explicitly calls the default (parameterless) public constructor of the base class using base(). 
    • If Derived's public constructor didn't have the : base() call, the compiler would implicitly insert a call to the parameterless public constructor of the base class.
  • Derived public constructor: public Derived() is called after the base class constructor has finished executing.
  • A protected constructor in C# is called only from within the class itself or from a derived class. It is not accessible from outside those classes.
    • protected constructor called?
      • From a derived class constructor
      • From a static or factory method inside the same class or subclass

 

 

 


Related Question