Friday, August 26, 2011

The type initializer for ... threw an exception

I was given some old code that I needed to port/partially rewrite.  The code had some funky things like a class trying to reference a static class as its base (which C# doesn't allow).  My guess is someone started to rewrite the code before they checked it into source control and never completed it.

Anyhow, I wrote a test app for this code after making a few tweaks and when this particular object was initialized it hit the declaration for the constructor and quit.  For some reason, .NET didn't throw any exceptions; it just stopped executing the code.

I wrapped my call with a try catch and caught the following: "The type initializer for 'NameOfClassICalled' threw an exception".  [This was a TypeInitializationException.]

After carefully stepping through the code I found my simple yet elusive mistake.  The code was initializing the base class which has static methods it was trying to load.  These static methods used the ConfigurationManager which uses the App.config... which I failed to include in my project.

Adding my app.config with the proper entries and I was off to the cases.  Reminder:  The parent assemblies config is the one that is used by assemblies called during execution.

No comments:

Post a Comment