Following the Type-Safe Enum Pattern, I created a small type-safe enum class. When the main dialog is first invoked, after it calls InitializeComponent, it invokes the constructor of another class, which tries to set one of its class variables to one of the static instances of the type-safe enum class. The issue is that all of these instances (and the class it seems) are null, thus causing the program to crash.
How do I get the program to construct that class and all of its instances first? I'm somewhat confused because I thought that static instances were created at the start of the program, so why does it not do it in this case?
Here's the condensed version of the code that's failing me: The type-safe enum pattern implementation:
public sealed class Types
{
public static readonly Types INVALID = new Types(-1, "Invalid");
... (other static instances and other implementations of the type-safe enum pattern)
}
The initialization of the main dialog:
public dlgMain()
{
InitializeComponent();
m_OtherClass = new OtherClass();
...
}
The constructor for OtherClass
public OtherClass()
{
m_eType = Types.INVALID; // Crash!! the entire type-safe enum class and its static members are null!
...
}
EDIT: Ok, here was the problem,
public sealed class Types
{
public static readonly Types INVALID = new Types(-1, "Invalid");
... (other static instances)
private static Dictionary<string, Types> mappings = new Dictionary<string, Types>(6); // There are 6 static types
private Types(int val, string name)
{
m_value = value; m_name = name;
mappings[name] = this; // This was causing the error, mappings is null
}
}
How do I get the program to construct that class and all of its instances first? I'm somewhat confused because I thought that static instances were created at the start of the program,
This is actually not true. Static data is created at some point prior to the first use of the type containing the static data. This is often initialized just prior to "using" the values, but not at program startup. (It shouldn't matter in this case, though.)
so why does it not do it in this case?
It actually likely is doing this properly. The problem is more likely within your constructor for Types
. When the static constructor runs, it needs to initialize each readonly
instance of Types
. If the constructor expects the static data to already be initialized or some other similar issue, this can cause an exception to be thrown.
I recommend putting a breakpoint within your Types
constructor (and any other constructors being used to initialize your static data). This will typically help diagnose and discover the real problem.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With