C# HashSet<T>.Remove: Syntax, Return Value, and Performance
See how HashSet<T>.Remove works in C#: return values, RemoveWhere for conditional deletion, performance behavior, and common pitfalls.

Removing an element from a HashSet<T> in C# is a straightforward operation, but the return value, performance behavior, and thread-safety rules are the parts that matter in real code. The examples below show the core Remove syntax, how to delete matching items with RemoveWhere, and the pitfalls to avoid.
Remove Syntax and Return Value
The method takes a single argument of type T and returns a bool:
var activeIds = new HashSet<int> { 101, 202, 303 };
bool removed = activeIds.Remove(202);
Console.WriteLine(removed); // True
Console.WriteLine(activeIds.Count); // 2The return value is the key detail: true means the element was found and removed, false means it was not in the set. The set itself never throws when the value is missing, so you can call Remove unconditionally without wrapping it in a try block.
This behavior differs from Dictionary<TKey, TValue>, where the indexer throws a KeyNotFoundException for missing keys. With HashSet<T>.Remove, the boolean result is the signal you use to decide whether subsequent logic should run.
What Happens When the Element Is Missing
Calling Remove on a value that does not exist leaves the set unchanged and returns false:
var tags = new HashSet<string> { "api", "database" };
bool removedMissing = tags.Remove("cache");
Console.WriteLine(removedMissing); // False
Console.WriteLine(tags.Count); // 2This makes Remove safe to call repeatedly. A common pattern is to use the return value to coordinate work between threads or to decide whether a resource should be released:
if (pendingJobs.Remove(jobId))
{
// This thread won the race; only it should process the job.
}Because the operation is atomic only under external synchronization (see the thread-safety section below), this pattern requires a lock or a concurrent collection when multiple threads touch the same set.
Removing Multiple Elements with RemoveWhere
When you need to delete every element that satisfies a condition, RemoveWhere is the appropriate method. It accepts a Predicate<T> and removes all matching elements in a single pass:
var scores = new HashSet<int> { 10, 25, 40, 55, 70 };
int removedCount = scores.RemoveWhere(score => score > 50);
Console.WriteLine(removedCount); // 2
Console.WriteLine(string.Join(", ", scores)); // 10, 25, 40RemoveWhere returns the number of elements removed, which is useful for logging or for deciding whether a follow-up operation is necessary. It mutates the set in place, so it is more efficient than iterating and calling Remove for each match, especially when many elements qualify.
Performance Characteristics
HashSet<T>.Remove has an average time complexity of O(1) because the set stores elements in buckets derived from the hash code of each value. The runtime computes the hash, locates the bucket, and removes the element without scanning the entire collection.
This is a meaningful difference from List<T>.Remove, which performs a linear scan and has O(n) complexity:
| Collection | Remove by value | Complexity |
|---|---|---|
| HashSet<T> | O(1) average | Hash lookup |
| List<T> | O(n) | Linear scan |
The practical consequence: if you remove elements frequently from a collection that can grow large, a HashSet<T> avoids the repeated linear scans that a List<T> would incur. For very small collections (a handful of items), the difference is negligible, and a list may be simpler if order matters, since HashSet<T> does not preserve insertion order.
The O(1) claim depends on a well-distributed hash function. For custom types, a poor GetHashCode implementation can degrade removal to near O(n) because many elements land in the same bucket. If you store custom objects, make sure GetHashCode distributes values evenly.
Thread Safety and Concurrent Removal
HashSet<T> is not thread-safe. If one thread calls Remove while another thread enumerates the set or calls Add, the behavior is undefined and can throw InvalidOperationException or corrupt internal state. The foreach enumeration in particular fails if the set is modified during iteration.
For concurrent scenarios, use a ConcurrentDictionary<T, byte> or ConcurrentDictionary<T, T> as a set, or guard all access with a lock:
private readonly object _sync = new object();
private readonly HashSet<string> _active = new HashSet<string>();
public bool TryDeactivate(string id)
{
lock (_sync)
{
return _active.Remove(id);
}
}A lock is sufficient when the set is small or when contention is low. When the set is large and accessed frequently from many threads, a concurrent collection avoids the lock overhead but changes the API surface, since ConcurrentDictionary uses TryRemove instead of Remove.
Common Mistakes and Edge Cases
One frequent mistake is calling Remove inside a foreach loop. The enumerator invalidates when the set changes, so the loop throws. Use RemoveWhere or collect the values to remove first, then remove them after the loop.
Another edge case is removing null from a HashSet<string>. null is a valid element for reference types, and Remove(null) works correctly as long as the comparer allows it, which the default comparer does.
For custom types, the default equality comparer uses GetHashCode and Equals. If you override Equals but not GetHashCode, two objects that compare equal can produce different hash codes, so Remove may not find the item. If a mutable object's hash code changes after it is inserted, removal can also fail. Always override both methods together, and avoid changing the fields used by GetHashCode while an object is stored in a set.
Remove does not shrink the internal bucket array. After removing many elements, the set keeps its allocated capacity. If memory usage matters and the set has been permanently reduced, you can call TrimExcess to release unused slots, though this is rarely necessary for typical workloads.
Choosing Between Remove, RemoveWhere, and Clear
The three removal operations serve different purposes:
Remove(value)deletes one specific element and reports whether it existed.RemoveWhere(predicate)deletes all elements matching a condition and returns the count.Clear()deletes every element and resets the set to empty.
Use Remove when you have a concrete value and need to know whether it was present. Use RemoveWhere when the removal condition is a rule rather than a value. Use Clear when you want to empty the set and plan to reuse the same variable. As with Remove, Clear keeps the internal bucket array allocated, so it is not a way to release memory; if you no longer need the set, let it go out of scope or reassign a new instance.
Try matching browser tools
All toolsSmall utilities that fit C# work — they run entirely in this browser tab, so nothing you paste leaves your device.
Related C# guides
All C# guidesC# Dispose vs Destructor: Key Differences Explained
c# dispose vs destructor: Understand the difference between Dispose and destructors in C#, when each runs, and how to manage unmanaged resources correctly.
C# Variable Declaration: Syntax and Practical Usage
Learn how to declare variables in C# with explicit types, var, and nullable annotations, and understand how defaults, scope, and readability affect your choices.
C# Primary Constructors for Classes: Syntax and Usage
Learn how to use C# primary constructors for classes: syntax, initialization, dependency injection, and limitations with practical examples.
C# IComparer: Custom Sorting with IComparer<T>
Learn how to implement IComparer<T> in C# to define custom sort order for arrays and lists, handle nulls, and avoid common performance pitfalls.
More in C#
All C# guidesThe guides filed next to this one in C#, in library order.