Dictionary dict;
what's the diff between
dict.add(key, value) and dict[key] = 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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With