Search code examples
c#.netdictionaryresharpercode-inspection

Resharper inspection issue "Redundant dictionary 'ContainsKey' before adding to the collection"


Resharper is throwing this inspection issue:

Redundant dictionary 'ContainsKey' before adding to the collection

At this part of the code:

var userPref = new Preferences { Key = key, Value = value };

if (this.preferencesDictionary.ContainsKey(key))
{
    this.preferencesDictionary[key] = userPref;
}
else
{
    this.preferencesDictionary.Add(key, userPref);
}

return this;

I don't really think this is redundant. It is an error that I should skip? Or is there really an improvement here?


Solution

  • While the getter for the indexer of Dictionary<TKey, TValue> throws a KeyNotFoundException when the key is not found, the setter inserts the value into the dictionary if the key is not found.

    Demo

    See the docs here.

    Property Value

    The value associated with the specified key. If the specified key is not found, a get operation throws a KeyNotFoundException, and a set operation creates a new element with the specified key.

    preferencesDictionary[key] looks like you are calling the getter here, but since it is followed by the assignment operator =, you are actually calling the setter.