Unnecessary call to 'Contains' for sets
Unnecessary call to 'Contains' for sets
Microsoft docsDescription
Both System.Collections.Generic.ISet1.Add(0) and System.Collections.Generic.ICollection1.Remove(0) perform a lookup, which makes it redundant to call System.Collections.Generic.ICollection1.Contains(0) beforehand. It's more efficient to call System.Collections.Generic.ISet1.Add(0) or System.Collections.Generic.ICollection1.Remove(0) directly, which returns a Boolean value indicating whether the item was added or removed.
This logic also applies to System.Collections.Immutable.IImmutableSet1.Add(0) and System.Collections.Immutable.IImmutableSet1.Remove(0), except that they either return a new set if the item is added or removed, or the original set if it wasn't.
Cause
An System.Collections.Generic.ISet1.Add or System.Collections.Generic.ICollection1.Remove call is guarded by a call to System.Collections.Generic.ICollection1.Contains. Or, an System.Collections.Immutable.IImmutableSet1.Add or System.Collections.Immutable.IImmutableSet1.Remove call is guarded by a call to System.Collections.Immutable.IImmutableSet1.Contains.
How to fix violations
Replace the call to System.Collections.Generic.ICollection1.Contains(0) (or System.Collections.Immutable.IImmutableSet1.Contains(0)) that's followed by a call to System.Collections.Generic.ISet1.Add(0) or System.Collections.Generic.ICollection1.Remove(0) (or System.Collections.Immutable.IImmutableSet1.Add(0) or System.Collections.Immutable.IImmutableSet1.Remove(0)) with a single call to the latter method.
Example
void Run(ISet<string> set)
{
if (!set.Contains("Hello World"))
{
set.Add("Hello World");
}
}
void Run(ISet<string> set)
{
set.Add("Hello World");
}When to suppress
It's safe to suppress this warning if performance isn't a concern.