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);
- Some other way
Источник: https://stackoverflow.com/questions/448 ... performant
Мобильная версия