I have my Dictionary declared like this:
private static Dictionary<string, Dictionary<string, string>> myDictionary;
I want to initialize it globally. The closest I have come initializes the outer Dictionary, but still leaves me with a null reference to the inner Dictionary:
private static Dictionary<string, Dictionary<string, string>> myDictionary
= new Dictionary<string, Dictionary<string, string>>();
I need to avoid initializing it in a method, because I don't want to force the user to call a method before being able to use my class. The user only has access to static methods. I could create a singleton when they call one of the methods, but that's dirty.
How can I declare both dictionaries globally? Something along the lines of one of these (although neither compile):
private static Dictionary<string, Dictionary<string, string>> myDictionary
= new Dictionary<string, new Dictionary<string, string>>();
or
private static Dictionary<string, string> inner = new Dictionary<string, string>();
private static Dictionary<string, Dictionary<string, string>> myDictionary
= new Dictionary<string, inner>();
Use the static constructor like this (assuming that the myDictionary
variable is in a class called MyClass
) :
public class MyClass
{
private static Dictionary<string, Dictionary<string, string>> myDictionary;
static MyClass()
{
//Initialize static members here
myDictionary = new Dictionary<string, Dictionary<string, string>>();
myDictionary.Add("mykey", new Dictionary<string, string>());
...
}
}
The framework will make sure that the static constructor is automatically executed before you access any member of the class.
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