Here I add something to a Dictionary
:
dictionary.Add(dictionaryKey, value);
if dictionaryKey
already exists, an ArgumentException
will be thrown. Its message is fairly generic:
An item with the same key has already been added.
If my call to dictionary.Add
is inside of a loop or a helper function, it can be hard to tell immediately what key has already been added that is throwing this exception. I would like to know this as easily and as soon as possible.
There are a few options.
1)
if (dictionary.ContainsKey(dictionaryKey))
{
throw new ArgumentException($"An item with the same key ({dictionaryKey}) has already been added.");
}
dictionary.Add(dictionaryKey, value);
try
{
dictionary.Add(dictionaryKey, value);
}
catch (ArgumentException argumentException)
{
throw new ArgumentException($"An item with the same key ({dictionaryKey}) has already been added.");
}
I know setting up a try/catch block takes a performance hit, but it seems running dictionary.ContainsKey(dictionaryKey)
would mean an additional lookup each time too. Which of these options is most performant?
.NET Core introduced the TryAdd
method, that allows to do it with a single lookup:
if (!dictionary.TryAdd(key))
{
throw new ArgumentException($"An item with the same key ({key}) has already been added.");
}