I had a weird issue arise after using CodeMaid to clean up my code. Now, the class which holds all my global variables and functions is throwing exceptions and I can’t figure out why.
The outer exception is thrown in GlobalClass.GetID(): TypeInitializationException.
The inner exception is: Object reference not set to an instance of an object
Here’s an example of some code that is causing this.
The library
namespace ErrorCode //Library
{
public static class GlobalClass
{
private static int _globalid = 0; //Never reached
public static int GlobalID
{
get
{
return _globalid;
}
} //Read-Only
public static int GetID()
{
retun _globalid++; //Crashes here with TypeInitialzationException
}
}
public class Entity
{
private int _id;
public int ID
{
get
{
return _id;
}
}
public Entity()
{
_id = GlobalClass.GetID(); //Crashes here with object reference not set to an instance of an object?
}
}
}
The actual program
using ErrorCode;
namespace MainProgram //The program that will run
{
public class Program
{
public Entity e = new Entity(); //Triggers GlobalClass.GetID()
}
}
Any ideas?
You edited your code down too much and removed the real cause of the exception. A class with a field initializer like this:
is not directly supported by the CLR. The compiler rewrites this code, it creates a static constructor for the class (or modifies an existing one) and writes it like this instead:
It does this for all the static fields with an initializer. One of which is throwing the exception in your case, we can’t see it in your snippet. One way to chase it down is to force the debugger to stop on the exception, Debug + Exceptions, tick the Thrown checkbox for CLR exceptions.