Pages

Topics

Tools

↑↓navigate↵openescclose
All guides

C# HashSet Add: Behavior, Performance, and Common Pitfalls

C# HashSet.Add returns a bool that tells you whether an item was inserted. See how duplicates are handled, performance tradeoffs, and common pitfalls.

~4 min readC#
#HashSet#C# Collections#Performance#Data Structures
Illustration of adding elements to a C# HashSet, showing duplicate rejection and unique element storage

HashSet<T>.Add inserts an element into a hash-based set and returns a bool that tells you whether the element was actually added. If the element is already present, it returns false and leaves the set unchanged. Understanding this behavior is the first step to using HashSet<T> effectively in C#.

What Add Returns and Why It Matters

Add returns true if the element was not already present and was successfully added. It returns false if the element already exists in the set. This return value is often overlooked, but it lets you combine a lookup and an insert in one operation.

csharp
var set = new HashSet<string>(); bool firstAdd = set.Add("apple"); // true bool secondAdd = set.Add("apple"); // false

The false result does not throw an exception; it simply indicates that the set already contained the element. Use this in algorithms that need to track visited items, deduplicate input, or count first occurrences.

How HashSet Handles Duplicates

HashSet<T> decides whether two elements are duplicates by using an equality comparer. By default, it uses EqualityComparer<T>.Default. For most value types, this compares values. For reference types, it compares references unless the type overrides Equals and GetHashCode. If you need different equality rules, pass an IEqualityComparer<T> to the HashSet constructor.

csharp
var set = new HashSet<int> { 1, 2, 3 }; set.Add(3); // false, 3 is already present

For reference types, default behavior can be surprising. Two different objects with identical field values are considered different unless equality is customized.

csharp
public class Person { public string Name { get; set; } } var set = new HashSet<Person>(); var p1 = new Person { Name = "Alice" }; var p2 = new Person { Name = "Alice" }; set.Add(p1); // true set.Add(p2); // true, because the references differ

If you want value-based equality, override Equals and GetHashCode on the type, or supply a custom comparer.

Using Add with Custom Types

Override GetHashCode and Equals when you want objects to be equal based on specific fields. This keeps Add, Contains, and Remove consistent.

csharp
public class Person { public string Name { get; set; } public override bool Equals(object obj) { return obj is Person other && Name == other.Name; } public override int GetHashCode() { return Name?.GetHashCode() ?? 0; } }

Now two Person instances with the same Name are considered equal, and the second Add returns false.

Alternatively, pass an IEqualityComparer<T> to the constructor. This is useful when the type comes from a library or when different contexts need different equality rules.

csharp
public class PersonNameComparer : IEqualityComparer<Person> { public bool Equals(Person x, Person y) { if (ReferenceEquals(x, y)) return true; if (x is null || y is null) return false; return x.Name == y.Name; } public int GetHashCode(Person obj) { return obj?.Name?.GetHashCode() ?? 0; } }
csharp
var set = new HashSet<Person>(new PersonNameComparer()); set.Add(new Person { Name = "Alice" }); // true set.Add(new Person { Name = "Alice" }); // false

Performance Characteristics of Add

HashSet<T>.Add has an average time complexity of O(1) because the set is backed by a hash table. The hash code of the element determines a bucket, and a single lookup is usually enough to detect duplicates. In the worst case, when many elements collide, lookup degrades toward O(n), but the .NET implementation keeps collisions low by resizing the internal storage.

Resizing is O(n) because existing elements must be rehashed and redistributed, but it happens infrequently. The amortized cost of Add is still O(1).

HashSet<T> uses more memory than List<T> because of hash-table overhead. That overhead is the tradeoff for fast membership checks and duplicate detection.

When to Prefer HashSet over List

List<T>.Add does not check for duplicates; it simply appends an item. If you need to prevent duplicates in a List, you must call Contains before adding, which makes the operation O(n). HashSet<T>.Add performs that duplicate check internally in O(1) average time.

OperationList<T>HashSet<T>
Add at endO(1), no duplicate checkO(1) average, returns false for duplicates
ContainsO(n)O(1) average
UniquenessNot enforcedEnforced automatically
Memory overheadLowHigher
Order preservedYesNo

Use HashSet<T> when you need to enforce uniqueness and perform fast membership checks. Use List<T> when you need to preserve insertion order, allow duplicates, or when membership checks are rare and the collection is small.

Common Mistakes and Edge Cases

A common mistake is ignoring the return value of Add. The bool tells you whether the element was newly inserted or was already present. If you ignore it, you lose that distinction without a separate Contains call.

Another issue is mutating an object after adding it to a HashSet. If you change a field that participates in GetHashCode, the object's bucket becomes stale. Contains and Remove may no longer find it. Avoid mutating objects used in hash-based collections.

HashSet<T> allows null for reference types. Adding null works with the default comparer, and Contains(null) works as expected. If you supply a custom comparer, make sure it handles null if you plan to add it.

HashSet<T> is not thread-safe. If multiple threads modify the same set, synchronize access with a lock or use a concurrent collection such as ConcurrentDictionary<T, byte> as a stand-in set.

Choosing Between HashSet and Dictionary

A Dictionary<TKey, TValue> stores key-value pairs, while a HashSet<T> stores only unique elements. If you need to associate data with each unique item, use a Dictionary. If you only need to track uniqueness, HashSet is simpler and lighter.

csharp
// HashSet for uniqueness var uniqueNames = new HashSet<string>(); uniqueNames.Add("Alice"); // Dictionary for key-value mapping var nameAges = new Dictionary<string, int>(); nameAges["Alice"] = 30;

Both rely on the same hash-table concepts, so their lookup and insert behavior is similar. The main decision is whether you need a value associated with each key.

Try matching browser tools

All tools

Small utilities that fit C# work — they run entirely in this browser tab, so nothing you paste leaves your device.

All C# guides

More in C#

All C# guides

The guides filed next to this one in C#, in library order.