JetBrains Rider 2024.3 Help

Code inspection: Can simplify 'Contains' before 'Add'

The Add method in HashSet<T> in C# is designed not to add duplicates to the set. If the element is already in the set, the method will just return false and will not throw any exceptions. Therefore, calling Contains before Add is redundant in this case.

void AddNumber(HashSet<int> hashSet, int number) { if (hashSet.Contains(number) == false) { hashSet.Add(number); } }
void AddNumber(HashSet<int> hashSet, int number) { hashSet.Add(number); }

This also applies to custom implementations of the ISet<T> interface, where the Add method must behave in the same way.

Last modified: 08 April 2024