Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How do I Initialize dictionary inside dictionary c#

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}}

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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" } } }
};
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading