I’m adding items to a StringDictionary and it’s possible that a duplicate key will come up. This will of course throw an exception.
If the chance of duplicates is very low (ie it will rarely happen), am I better off using a Try Catch block and leaving it unhandled, or should I always do a .ContainsKey check before adding each entry?
I’m assuming that if the likelihood of duplicate keys was high, then allowing exceptions would be a poor decision as they are expensive.
Thoughts?
Edit
I used reflector on the generic Dictionary and found the following for ContainsKey and TryGetValue, as both were mentioned below.
public bool TryGetValue(TKey key, out TValue value)
{
int index = this.FindEntry(key);
if (index >= 0)
{
value = this.entries[index].value;
return true;
}
value = default(TValue);
return false;
}
And
public bool ContainsKey(TKey key)
{
return (this.FindEntry(key) >= 0);
}
Am I missing something, or is TryGetValue doing more work than ContainsKey ?
I appreciate the responses, and for my current purpose I’m going to go with doing a ContainsKey call as the collection will be small, and the code more readable.
How to approach this depends on what you want to do if a collision happens. If you want to keep the first inserted value, you should use
ContainsKeyto check before inserting. If, on the other hand, you want to use the last value for that key, you can do like so:As a side note: I would probably, if possible, use
Dictionary<string, string>instead ofStringDictionary. If nothing else that will give you access to some more Linq extension methods.