by Ahmed
9. December 2010 14:11
I've blogged about using static constuctors for Singletonsbefore. Static constructors are invoked only once before any (instance or static) member of the class can be executed. Based on this behavior, it provides an ideal thread-safe initialization section in many scenarios.
There is however one particular behavior of static constructors that is good to know. If an unhandled exception occurs in a static constructor then the class is effectively unusable. Any other client code trying to use any static/instance member of the *failed* class can expect a type initialization exception in return. Unlike instance constructors, the runtime will not try to re-execute the static constructor if it failed once since static constructors are only supposed to execute once.
For developers it's something important to keep in mind if you tend to use static constructors frequently. Either explicitly handle the exception or try not to put any code in there that can result in an error e.g. a call to a DB or web service. Stuff like this should be put in a separate initialization method that should be called once.