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.
Syntax: public bool ContainsKey (TKey key); Here, the key is the Key which is to be located in the Dictionary. Return Value: This method will return true if the Dictionary contains an element with the specified key otherwise, it returns false.
Solution 2 Your item with the same key has already been added is also an utra general error, but typically it can be trying to set the same key in a database (or forgetting to set a key with no default value, hence for instance if an int, then all rows would be 0, de default) or a dictionary.
The Dictionary throws a KeyNotFound exception in the event that the dictionary does not contain your key. As suggested, ContainsKey is the appropriate precaution.
Add() Method is used to add a specified key and value to the dictionary. Syntax: public void Add (TKey key, TValue value);
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 ContainsKey
to check before inserting. If, on the other hand, you want to use the last value for that key, you can do like so:
// c# sample:
myDictionary[key] = value;
As a side note: I would probably, if possible, use Dictionary<string, string>
instead of StringDictionary
. If nothing else that will give you access to some more Linq extension methods.
I would do the Contains check.
My reasoning is exceptions should be saved for those things that just shouldn't happen. If they do then alarm bells should be rang and calvery brought in. Just seems odd to me to use exceptions for known issue case handling especially when you can test for it.
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