Frage

I just received an exception when I try to reference a static variable in another class, which is also statically initialized. This worked before, and for some reason it fails now. The only changes I made were resetting Visual Studio (2010) to its default setting, which I can't imagine to be the reason for this. Any other code I added didn't touch any of the affected parts either.

This is my code


WinForms class 'MainForm':

partial class MainForm : Form
{ 
    // ...

    private RefClass convMan;
    private Dictionary<EnumType, string> LogNames = RefClass.LogNames;

    // ...

   public MainForm() { .... }
}

Referenced class 'RefClass':

class RefClass
{
    // ...

    public enum EnumType { TypeOne = 0, TypeTwo = 1, TypeThree = 2 };

    public static Dictionary<EnumType, string> LogNames = new Dictionary<EnumType, string>()
    {
        { EnumType.TypeOne, "Text0" },
        { EnumType.TypeTwo, "Text1" },
        { EnumTypy.TypeThree, "Text2" }
    };

}

The error I get now is (translated from German):

An unhandled exception of type "System.TypeInitializationException" occurred.

Additional information: The type initializer for "RefClass" threw an exception.

which has the InnerException

System.ArgumentException

So, as far as I'm concerned, my static dictionary should be initialized once it gets accessed, thus when my Form class references it. I tried debugging to see if the static dictionary is initialized before it gets referenced in the Form class, which is not the case. Also, when I stop at a breakpoint for the reference line, the variable LogNames is null.

I'm really confused as to why this happens, it all worked before.

War es hilfreich?

Lösung

I found my error, the exceptions I got were quite misleading though. It was a problem with a different dictionary than the one I referenced. It probably didn't get initialized in the first place because something before that failed (If someone can clear this up, please feel free to do so!). Basically what I did wrong was using a two-directional dictionary and adding a value twice. This should normally produce a normal exception, but since it was done statically it got wrapped into a TypeInitializationException. I had a deeper look into the exact stacktrace of the inner exception and found where the exception originated from. Maybe this helps someone in the future...

Andere Tipps

I had a simular issue getting the same exception. Found that my static constructor for my utility class was generating the exception. Took some time locating since the description of the exception was misleading.

As @Yeehaw mentioned, it appears that the exception gets wrapped, so the common denominator here I would say is that the class/object is static.

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top