Need help manually adding to a dictionary

Viewed 202

I am confused I am trying to manually add entries to a Dictionary but its throwing an error at the first comma. Any help is appreciated thank you.

        private Dictionary<string, Dictionary<string, string>> packData =
        new Dictionary<string, Dictionary<string, string>>()
        {
            {
                "Test", //issue here
                {
                    "Test" , "Test"
                }
            };
        };

enter image description here

1 Answers

You'll want to be explicit about the inner dictionary:

    new Dictionary<string, Dictionary<string, string>>()
    {
        {
            "Test", 
            new Dictionary<string, string> 
            {
                "Test" , "Test"
            }
        };
    };

The rule to follow here is "imagine if the thing in the braces was replaced with a call to Add". In your original code, we would have lowered this to:

    temp = new Dictionary<string, Dictionary<string, string>>();
    temp.Add("Test", { "Test", "Test" });

Which is not legal code. But

    temp = new Dictionary<string, Dictionary<string, string>>();
    temp.Add("Test", new Dictionary<string, string>(){ "Test", "Test" });

is legal, and in turn corresponds to

    temp = new Dictionary<string, Dictionary<string, string>>();
    temp2 = new Dictionary<string, string>();
    temp2.Add("Test", "Test");
    temp.Add("Test", temp2);

I often find when I'm confused that it helps to "lower" the code into its more basic form to understand what's going on.

There are some situations in which the compiler is smarter about understanding the intended meaning of nested braces like in your original code, but unfortunately this is not one of them. See the specification for more details about what is and is not supported; you'll want to search for "object initializers" and "collection initializers".

Related