To answer the question first, we need to look at the purpose of the vocabulary and underlying technologies.
Dictionary is a list of KeyValuePair<Tkey, Tvalue> , where each value is represented by its unique key. Say we have a list of your favorite dishes. Each value (food name) is represented by its unique key (position = how much you like this food).
Code example:
Dictionary<int, string> myDietFavorites = new Dictionary<int, string>() { { 1, "Burger"}, { 2, "Fries"}, { 3, "Donuts"} };
Say you want to stay healthy, you change your mind, and want to replace your favorite Burger with salad. Your list is still your favorites list; you will not change the nature of the list. Your favorite will remain number one on the list, only its value will change. This is when you call this:
myDietFavorites[1] = "Salad";
But do not forget that you are a programmer, and from that moment you finish your sentences; you refuse to use emojis because they will throw a compilation error, and the entire list of favorites is index based.
Your diet has changed too! Thus, you will change your list again:
myDietFavorites[0] = "Pizza"; myDietFavorites.Add(0, "Pizza");
There are two possibilities with a definition: you either want to give a new definition for something that did not exist before, or you want to change a definition that already exists.
The add method allows you to add an entry, but only under one condition: the key for this definition may not exist in your dictionary.
Now we will look under the hood. When you create a dictionary, your compiler makes a reservation for the bucket (spaces in memory to store your records). The bucket does not store keys as you define them. Each key is hashed before moving into the bucket (defined by Microsoft), it is worth mentioning that the value of the part remains unchanged.
I use the CRC32 hash algorithm to simplify my example. When you define:
myDietFavorites[0] = "Pizza";
What happens to the bucket: db2dc565 "Pizza" (simplified).
When you change the value with:
myDietFavorites[0] = "Spaghetti";
You have x, which will again be db2dc565 , then you will find this value in your bucket to find it there. If it is there, you simply rewrite the value assigned to the key. If it is not, you will put your value in a bucket.
When you call the Add to your dictionary function, for example:
myDietFavorite.Add(0, "Chocolate");
You have a hash to compare it with units in a bucket. You can put it in a bucket only if it is not there .
It is very important to know how this works, especially if you work with dictionaries like string or char. It is case sensitive due to hashing. So, for example, "name"! = "Name". Let us use our CRC32 to depict this.
Value for "name": e04112b1 Value for "Name": 1107fb5b