HashSet<T> · C#

Contains

Tests membership with the set's comparer.

public bool Contains(T item)

Complexity

ExpectedO(1)
Worst caseO(n)
Extra spaceO(1)

Assumes: Good hash distribution.

One hash and a short chain walk, compared with a List<T>.Contains scan of the whole list.

Tested example

var words = new HashSet<string>(StringComparer.OrdinalIgnoreCase) { "Apple" };
bool hasApple = words.Contains("apple"); // the comparer decides what "equal" means
bool hasPear = words.Contains("pear");
Assert.True(hasApple);
Assert.False(hasPear);
Runs in the test suite on .NET 10 (SDK 10.0.403), C# 14 · examples/csharp/Bekadan.Dsa.Examples.Tests/Collections/HashSetExamples.cs

Parameters

item
The element to test.

Behaviour

Returns
Whether it is present.
Errors and preconditions
None.
Changes
Nothing.
Memory and invalidation
No allocation.