Today I had a discussion with my colleague and concluded following points. Kindly throw some light if all are correct or some modification is required.
- When static constructor is not defined in class, static fields are initialized just before their use.
- When static constructor is defined in class, static fields are initialized just before their use or as part of (before) instance creation.
- If no static field is accessed within a static method and that static method is called. the static fields will be initialized only if static constructor is defined in that class.
- If possible static constructor should be avoided in a class.
1.-3.You cannot exactly know when it happens and so you cannot depend on it. A static constructor will give you a little control what happens when it get called.
4.Static constructors are slow
The exact timing of static constructor execution is implementation-dependent, but is subject to the following rules:
referenced.
different classes is not specified.
All of your points are correct.
The reason static constructors should be avoided is because the compiler injects code everywhere any method of the class is called to check that the static constructor has been called. This has a negative impact on performance.
What you can do is have a private static field in you class that is assigned a dummy value when the default (or other non static) constructor is called. This initializes all static fields on object creation.