Explanation of Dictionary Initialisation Syntax (C#)

c#

Solution

Alright lets take a look at the code here:

Dictionary<string, int> d = new Dictionary<string, int>() 
{ 
    {"cat", 2}, 
    {"dog", 1}, 
    {"llama", 0}, 
    {"iguana", -1} 
};

a dictionary holds two things, a key, and a value. your declaration, `Dictionary<string, int>`, means the keys are strings, and the values are integers.

now, when your adding an item, for instance `{"cat", 2},`, the key is cat. this would be equivilent to you doing something like, `d.Add("cat", 2);`. a dictionary can hold anything, from `<string, string>` to `<customClass, anotherCustomClass>`. and to call it up you can use `int CAT = d["cat"];` to which the value of `int CAT` would be 2. an example of this would be:

Dictionary<string, int> dict = new Dictionary<string, int>() 
{ 
    {"cat", 1}
};
dict.Add("dog", 2);
Console.WriteLine("Cat="+dict["cat"].ToString()+", Dog="+dict["dog"].ToString());

in in there, your adding cat and dog with different values and calling them up

Problem

I found an example showing that a dictionary can be initialised as follows: ``` Dictionary<string, int> d = new Dictionary<string, int>() { {"cat", 2}, {"dog", 1}, {"llama", 0}, {"iguana", -1} }; ``` I don't understand how the syntax `{"cat", 2}` is valid for creating a Key-Value Pair. Collection initialisation syntax seems to be of the form `new MyObjType(){}`, while anonymous objects are of the form `{a="a", b="b"}`. What is actually happening here?

Original source