What is the difference between adding and [] in dictionary operation

Dictionary dict;

What's the difference between

dict.add (key, value) and dict [key] = value

+7
c #
source share
3 answers

dict[key] = value will add a value if the key does not exist, otherwise it will overwrite the value with this (existing) key.

Example:

 var dict = new Dictionary<int, string>(); dict.Add(42, "foo"); Console.WriteLine(dict[42]); dict[42] = "bar"; // overwrite Console.WriteLine(dict[42]); dict[1] = "hello"; // new Console.WriteLine(dict[1]); dict.Add(42, "testing123"); // exception, already exists! 
+16
source share

As Ahmad noted, dictionary[key] = value; will add a value if the key does not exist, or overwrite if it does.

On the other hand, dictionary.Add(key, value); throws an exception if key exists.

+5
source share

The Add operation will fail (throwing an ArgumentException ) if the key already exists in the dictionary. Operation [] will either add the key if it does not exist, or update it if the key exists.

+2
source share

All Articles