.TryAdd
to safely add keys to a Dictionary<K, V
> CS-R1123Instead of checking if a key exists using ContainsKey()
and then adding an element to a Dictionary<K, V>
, consider using the TryAdd()
method instead as it is a safer alternative that is easy to read and comprehend.
if (!dict.Contains(k))
{
dict.Add(k, v);
}
dict.TryAdd(k, v); // Returns a boolean value.