Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I initialize a global nested Dictionary globally?

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>();
like image 603
Evorlor Avatar asked Dec 25 '22 07:12

Evorlor


1 Answers

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.

like image 81
Yacoub Massad Avatar answered Dec 26 '22 22:12

Yacoub Massad