Initialize dictionary <string, List <string>>

I would like to know how can I declare / initialize a dictionary? Below is the error.

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

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

      

Error: Field initializer cannot refer to non-static field, method, or property MyList. This is not a List declaration starting at or later after the dictionary.

+3


source to share


3 answers


As Scott Chamberlain said in his response :

If these are not static field definitions, you cannot use field initializers like this, 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 a 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 }

};

      

+4


source


If these are not static field definitions, you cannot use field initializers like this, 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 }
        };
    }
}

      

+4


source


Dictionary<string, List<string>> myD = new Dictionary<string, List<string>>()
{
    {"tab1", new List<string> { "1" } },
    {"tab2", new List<string> { "1","2","3" } },
    {"tab3", new List<string> { "one","two" } }
};

      

+3


source







All Articles