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?
Alright lets take a look at the code here:
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 useint CAT = d["cat"];to which the value ofint CATwould be 2. an example of this would be:in in there, your adding cat and dog with different values and calling them up