#670 – Static vs. Instance Initialization
September 13, 2012 Leave a comment
Static fields and properties are data members associated with a class itself, rather with instances of that class. A static constructor can be used to initialize static members. Static fields can also be initialized when they are declared.
The first time that you reference a static member, the following occurs:
- All static fields are initialized
- The static constructor is called
- Your code, which accesses the static member, executes
If you reference an instance method, or create an instance of the class, before referencing any static members, the following occurs:
- All static fields are initialized
- The static constructor is called
- All instance fields are initialized
- The instance constructor is called
- Your code, which accesses an instance member, executes
For example, initializing an instance of a Dog leads to the output shown below.
Dog d = new Dog();