Declaring a dictionary is almost the same as declaring a list, but with one added detail—both the key and the value type need to be specified inside the arrow symbols:
Dictionary<keyType, valueType> name = new Dictionary<keyType,
valueType>();
To initialize a dictionary with key-value pairs, do the following:
- Use a pair of curly brackets at the end of the declaration.
- Add each element within its pair of curly brackets, with the key and the value separated by a comma.
- Separate elements with a comma, except the last element where the comma is optional:
Dictionary<keyType, valueType> name = new Dictionary<keyType,
valueType>()
{
{key1, value1},
{key2, value2}
};
An important note to consider when picking key values is that each key must be unique, and they cannot be changed. If you need to update a key, change its value in the variable declaration or remove the entire key-value pair and add another in code.
Just like with arrays...