ReSharper
 
Get ReSharper
Get your hands on the new features ahead of the release by joining the Early Access Program for ReSharper 2025.1! Learn more

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

Last modified: 08 April 2024

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.

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