What is the cleanest way to use dictionaries and protect against an unhandled ArgumentException
if the key already exists in the dictionary?
I'd like to say that I can always guarantee uniqueness upstream, but I'm dealing with legacy code and mildly corrupt data from an old bug in the system.
I find myself using this pattern frequently but wonder if there is a better way.
public void AddToDictionaryContainsKey(Dictionary<int,string> myDictionary, int myKey, string myValue )
{
if (!myDictionary.ContainsKey(myKey))
{
myDictionary.Add(myKey, myValue);
}
}
Maybe a try/catch block - but this seems less readable. The advantage is that if I ever do decide to log the problem I have a place to do it.
public void AddToDictionaryTryCatch(Dictionary<int, string> myDictionary, int myKey, string myValue)
{
try
{
myDictionary.Add(myKey, myValue);
}
catch (ArgumentException e)
{
// keep on truckin'
}
}
The dictionaries are relatively small (typically < 1000 entries) so I prefer readability over performance.
AddIfNotExist
method if you really want. \$\endgroup\$The advantage is that if I ever do decide to log the problem I have a place to do it
- and what prevents you from logging the problem in your first solution, every time whenContainsKey
is already true? : ) I can't see the advantage \$\endgroup\$