Initialize Dictionary<string, List<string>>

c#, dictionary

Solution

As Scott Chamberlain said in his answer:

If these are non static field definitions you can not use the field initializers like that, you must put the data in the constructor.

class MyClass
{
    Dictionary<string, List<string>> myD;        
    List <string> MyList;

    public MyClass()
    {
        MyList = new List<string>() { "1" };
        myD = new Dictionary<string, List<string>>()
        {
          {"tab1", MyList }
        };
    }
}

Additionally for Static field

private static List<string> MyList = new List<string>()
{    
   "1"
};

private static Dictionary<string, List<string>> myD = new Dictionary<string, List<string>>()
{
    {"tab1", MyList }

};

Problem

I would like to know how do I declare/initialize a dictionary ? The below one gives error. ``` Dictionary<string, List<string>> myD = new Dictionary<string, List<string>>() { {"tab1", MyList } }; List <string> MyList = new List<string>() { "1" }; ``` The error is: A field initializer cannot reference the non-static field, method, or property MyList. It is not List declaration coming in front or later after dictionary.

Original source