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?
While the getter for the indexer of
Dictionary<TKey, TValue>throws aKeyNotFoundExceptionwhen the key is not found, the setter inserts the value into the dictionary if the key is not found.Demo
See the docs here.
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.