What should StringDictionary::Add do with duplicates?

  • Thread starter Thread starter Norman Diamond
  • Start date Start date
N

Norman Diamond

It would be easy to write a short test program to call
StringDictionary::Add() twice with the same key string. But this would
reveal what the current version of StringDictionary happens to do today on
one computer. It is not wise to rely on such undocumented behaviour. So I
have to ask, what is StringDictionary::Add() supposed to do when called with
a key string that is already in the dictionary?

Having written programs that implemented hash tables before Microsoft
existed, I can easily imagine several possibilities:
1. Add the new entry. If someone subsequently enumerates the entire table
then they get all entries including duplicates. If someone asks for
one matching entry then they get one at random.
2. Replace the existing entry by the new one.
3. Reject the operation and return false, which would be possible
if Add's return type weren't void.
4. Reject the operation and generate an exception.
5. Reject the operation silently.
6. Generate a blue screen. Oops, this has to wait until Microsoft exists.

So, what is StringDictionary::Add() supposed to do in such a case, and does
MSDN say it somewhere?

To avoid relying on undocumented behaviour, it seems necessary to call
StringDictionary::ContainsKey() before every Add. I hope, I hope the answer
is documented somewhere instead.
 
I think the documentation for this method is very clear. You get
ArgumentException if "An entry with the same key already exists in the
StringDictionary.".
To have (2), use the indexer (documented as Item) which creates the
entry if not exist and replaces if already exist.
To have (1) or (3) or (5), you need to write your own collection.
To have one key - multiple values, use NameValueCollection.
 
Truong Hong Thi said:
I think the documentation for this method is very clear. You get
ArgumentException if "An entry with the same key already exists in the
StringDictionary.".

OK, thank you. So many times I read the page for StringDictionary::Add and
the main page for StringDictionary looking for things like "allows
duplicates" or "doesn't allow duplicates", and the remarks in the Add page.
I didn't think of reversing this kind of "searching logic". After you said
what to look at, I saw it, and it's very clear. Thank you.
 
Back
Top