Type initializer (static constructor) exception handling

Thorarin picture Thorarin · Aug 25, 2009 · Viewed 7k times · Source

I'm writing a WCF service in C#. Initially my implementation had a static constructor to do some one-time initialization, but some of the initialization that is being done might (temporarily) fail.

It appears that static constructors are only called once, even if the first (failed) attempt threw an exception? Any subsequent attempts to instantiate my class will immediately fail with a TypeInitializationException without the code actually being executed.

The C# language specification states that a static constructor is called at most once, but basically this makes an exception in there an error that you cannot ever recover from, even if you catch it?

Am I missing something here? I suppose I should move anything remotely dangerous to the service's instance constructor and manually check whether or not the class initialization was already succesfully completed earlier?

Answer

Barry Kelly picture Barry Kelly · Aug 25, 2009

The lesson here is pretty simple: don't do anything in a static constructor that could reasonably fail.