Adding Key, Values to Dictionary C#

Viewed 30
Dictionary<int,int> dic = new Dictionary<int,int>();

What is the difference between below to approach to add key, value to dictionary?

dic[key]=value;
dic[key]=value1;  //its allowing me to update the value for the same key. No error.

vs

dic.Add(key,value);
dic.Add(key,value1); //it doesn't allow to update the value to the key as key already exists.
1 Answers

This is the intended behavior of this property and the .Add method.

From the documentation on the Dictionary<TKey,TValue>.Item[TKey] Property:

Gets or sets the value associated with the specified key.
...
If the specified key is not found, [...] a set operation creates a new element with the specified key.

Compare that with the documentation on the Dictionary<TKey,TValue>.Add(TKey, TValue) Method method, which says that an ArgumentException will be thrown when "[a]n element with the same key already exists in the Dictionary<TKey,TValue>."

Related