Home > other >  How do I Initialize dictionary inside dictionary c#
How do I Initialize dictionary inside dictionary c#

Time:02-12

e.g. see the following code d1,d2 are fine but on d3 compiler throwing a fit.

var d1 = new Dictionary<string, string> { { "1", "1" } }; //works
var d2 = new Dictionary<string, Dictionary<string, string>> { { "1", d1 } }; //works
var d3 = new Dictionary<string, Dictionary<string, string>> { { "1", { { "1", "1" } } }} //does not work

Python does same and much simpler way

d1:dict={'1':1}
d2:dict = {'1':{'1':1}}

CodePudding user response:

You've left out the new Dictionary<string, string> part (and one closing }):

var d3 = new Dictionary<string, Dictionary<string, string>> { { "1", new Dictionary<string, string> { { "1", "1" } } } };
// −−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^−−−−−−−−−−−−−−−−−−−−^

You need to tell C# what concrete instance to create because you could be using a Dictionary subclass:

class SomeDictionarySubclass<K, V> : Dictionary<K, V> {
    // ...
}
// ...
var d3 = new Dictionary<string, Dictionary<string, string>> {
    { "1", new SomeDictionarySubclass<string, string> { { "1", "1" } } }
};
  •  Tags:  
  • c#
  • Related