Code inspection: 'ContainsKey' call is redundant before adding the item to the dictionary
This inspection reports an if statement that checks ContainsKey only to choose between Add and index assignment with the same key and the same value. In that pattern, the existence check is redundant because a single index assignment already handles both cases.
using System.Collections.Generic;
class C
{
void AddOrUpdate(Dictionary<int, int> map, int key, int value)
{
if (!map.ContainsKey(key))
{
map.Add(key, value);
}
else
{
map[key] = value;
}
}
}
using System.Collections.Generic;
class C
{
void AddOrUpdate(Dictionary<int, int> map, int key, int value)
{
map[key] = value;
}
}
This inspection only reports cases where the assigned value is equivalent and safe to evaluate once.
13 April 2026