0
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.
Theodor Zoulias
  • 34,835
  • 7
  • 69
  • 104
  • You answered your own question. The first is an update, the second is attempting to add a new key. Dictionaries can't have duplicate keys. – Bradford Dillon Sep 12 '22 at 17:46

1 Answers1

2

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>."

Theodor Zoulias
  • 34,835
  • 7
  • 69
  • 104
Donut
  • 110,061
  • 20
  • 134
  • 146