what the difference between add and [] in the dictionary operation
Dictionary dict;
what's the diff between
dict.add(key, value) and dict[ke开发者_开发问答y] = value
dict[key] = value
will add the value if the key doesn't exist, otherwise it will overwrite the value with that (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!
As Ahmad noted, dictionary[key] = value;
will add the value if the key doesn't exist, or overwrite if it does.
On the other hand, dictionary.Add(key, value);
will throw an exception if key
exists.
The Add
operation will fail (throws ArgumentException
) if the key already exists in the dictionary. The []
operation will either add the key if it doesn't exist or update it if the key does exist.
精彩评论