Debugging exceptions in type initializers
c#, debugging, visual-studio
Solution
Click Debug, Exceptions, (or press Ctrl+D, E) and tell Visual Studio to break whenever any exception is thrown. It will then break when the InnerException is thrown, before it gets wrapped in a TypeInitializationException, and it will break on the line that threw the exception.
Alternatively, look at the InnerException's call stack and see which of your field s it matches.
Or, try setting a breakpoint on every static initializer; the last one hit is the one that threw the exception.
Problem
I have a static class with no static constructor, but many static members. I throw a TypeInitializationException when the class is first used. I am breaking on CLR exceptions, and I have disabled 'Just My Code'. The problem is that I only get this exception when this class is first used; I don't break at the failing static field initializer. I could certainly remove the static members until I find the culprit, but is there an easier way? Does anyone have any tips for debugging static field initializations?