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.

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.
var set = new HashSet<string>();
bool firstAdd = set.Add("apple"); // true
bool secondAdd = set.Add("apple"); // falseThe 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.
var set = new HashSet<int> { 1, 2, 3 };
set.Add(3); // false, 3 is already presentFor reference types, default behavior can be surprising. Two different objects with identical field values are considered different unless equality is customized.
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 differIf 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.
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.
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;
}
}var set = new HashSet<Person>(new PersonNameComparer());
set.Add(new Person { Name = "Alice" }); // true
set.Add(new Person { Name = "Alice" }); // falsePerformance 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.
| Operation | List<T> | HashSet<T> |
|---|---|---|
| Add at end | O(1), no duplicate check | O(1) average, returns false for duplicates |
Contains | O(n) | O(1) average |
| Uniqueness | Not enforced | Enforced automatically |
| Memory overhead | Low | Higher |
| Order preserved | Yes | No |
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.
// 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 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.