As you've probably discovered, if you
Add(key, value)
to a
Dictionary
that already has an entry with the same
key
, it throws an
ArgumentException
. It is not possible to have multiple entries with the same
key
.
If you want to add the value if the key is not present then try this:
Dictionary<int, string> dict = new Dictionary<int, string>();
dict.Add(1, "umpteen");
dict.Add(2, "di");
if (!dict.Contains(1))
dict.Add(1, "mono");
if (!dict.Contains(3))
dict.Add(3, "three");
If all you want it to ensure that a
key-value pair exists in the
Dictionary
, no matter if there is already a
key-value pair with the same
key and either the same or a different value, then instead of
Add
ing to the
Dictionary
, just assign into it:
dict[1] = "mono";
dict[2] = "di";
dict[3] = "tri";
dict[4] = "quad";
None of those assignments threw an exception and all 4 entries in the
dict
are set.