Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c#

.net

Dictionary dict;

what's the diff between

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

like image 340
user496949 Avatar asked Nov 19 '10 03:11

user496949


2 Answers

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!
like image 196
Ahmad Mageed Avatar answered Sep 19 '22 10:09

Ahmad Mageed


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.

like image 21
Andrew Barber Avatar answered Sep 20 '22 10:09

Andrew Barber