
C#: Does a Static Constructor Always Run First?
There’s a common misconception — and it often shows up as an interview question: On the first access to a type, the very first thing that runs is the type’s static constructor. But if a static field is initialized with an instance of the same type, the order flips: the instance constructor can run before the static constructor. This is not a bug — it’s defined by the CLI/ECMA specification. Minimal example class MyLogger { static MyLogger inner = new MyLogger (); static MyLogger () { Console . WriteLine ( "Static" ); } private MyLogger () { Console . WriteLine ( "Instance" ); } } The expectation is often: Static Instance Actual output: Instance Static What the specification actually guarantees It’s important to separate two concepts: static field initializers (field initializers), the body of the static constructor ( static MyLogger() { ... } ). During type initialization, code runs in a fixed order: first — static field initializers (in declaration order), then — the body of the stati
Continue reading on Dev.to
Opens in a new tab


