开发者

what the difference between add and [] in the dictionary operation

开发者 https://www.devze.com 2023-01-25 16:55 出处:网络
Dictionary dict; what\'s the diff between dict.add(key, value) and dict[ke开发者_开发问答y] = valuedict[key] = value will add the value if the key doesn\'t exist, otherwise it will overwrite the val

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.

0

精彩评论

暂无评论...
验证码 换一张
取 消