Dictionary dict;
What's the difference between
dict.add (key, value) and dict [key] = value
dict[key] = value will add a value if the key does not exist, otherwise it will overwrite the value with this (existing) key.
dict[key] = value
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!
As Ahmad noted, dictionary[key] = value; will add a value if the key does not exist, or overwrite if it does.
dictionary[key] = value;
On the other hand, dictionary.Add(key, value); throws an exception if key exists.
dictionary.Add(key, value);
key
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.
Add
ArgumentException
[]