Search code examples
c#unhandled-exception

Unhandled exception of type 'System.TypeInitializationException' occurred in Unknown Module


For .NET I normally code in VB, but I'm having to work on a project in C#, and bumped into this weird issue.

I have 3 classes (Form1, and 2 added classes that call controls and methods on Form1).

To make life easier, in Program.cs I added:

public static Form1 form1 = new Form1(); // Place this var out of the constructor Application.Run(form1);

and then just call the Form1 stuff with something like:

Program.form1.ResetForm();

Here's where it gets weird though. I can use that exact line above on one class (say, clsFoo.cls) and it works fine, but, that exact same line (and any others that use Program.form1.) on clsBar.cls create the error in the title.

When running the program and it hits a line in clsBar.cls that uses that, I get this:

screenshot

And the error shown in the output:

Exception thrown: 'System.NullReferenceException' in YourProgram.exe An unhandled exception of type 'System.TypeInitializationException' occurred in Unknown Module. The type initializer for 'Your.Program' threw an exception.

From all that I can tell, I'm using the same exact namespaces, class names, Usings, etc. I've also set any relative controls on Form1's Modifiers to Public.

Not being super experienced w/C#, I'm kinda stuck on this one. Anyone know what's up?


Solution

  • Turned out that the code in that class was being called before the code initializing Form1 in Program.cs was called. Weird.