Skip to content

Latest commit

 

History

History
34 lines (24 loc) · 939 Bytes

File metadata and controls

34 lines (24 loc) · 939 Bytes

Pattern: Unnecessary call to Contains() for sets

Issue: -

Description

Both ISet<T>.Add(T) and ICollection<T>.Remove(T) perform a lookup, which makes it redundant to call ICollection<T>.Contains(T) beforehand. It's more efficient to call Add(T) or Remove(T) directly, which returns a Boolean value indicating whether the item was added or removed.

This logic also applies to IImmutableSet<T>.Add(T) and IImmutableSet<T>.Remove(T), except that they either return a new set if the item is added or removed, or the original set if it wasn't.

Example of incorrect code:

void Run(ISet<string> set)
{
    if (!set.Contains("Hello World"))
    {
        set.Add("Hello World");
    }
}

Example of correct code:

void Run(ISet<string> set)
{
    set.Add("Hello World");
}

Further Reading