In C#, HashSet.Add(item) puts one item into a set of unique items. Think of a guest list: writing a name that is already on the list does not add it a second time.
That is why Add returns a bool. It gives true when the item was new and was stored, and false when the set already held an equal item. A repeat is not an error; the set simply stays the same. This is different from Dictionary.Add(), which throws for a repeated key.
This is an instance member of HashSet<T> (System.Collections.Generic). Call it on a set variable, such as numbers.Add(...). A HashSet<T> is a class, so two variables can share one set. It keeps unique items only and does not promise any order.
Syntax
Call Add on a set variable and pass the item. Use the bool result if you care whether the item was new.
C#
HashSet<string> fruits = new HashSet<string>();
bool first = fruits.Add("apple"); // true: new item
bool second = fruits.Add("apple"); // false: already in the set
fruits.Add("banana"); // result ignored, that is fine
Call
What it does
fruits.Add("apple")
Stores "apple" and returns true if it was not in the set yet.
fruits.Add("apple") // again
Changes nothing and returns false. No exception.
if (!fruits.Add(x)) { ... }
Run code only for repeats, such as printing "duplicate found".
Add is an average O(1) call. Two items count as the same when the set's comparer says they are equal. By default that is Equals, so "Asha" and "ASHA" are different. Pass StringComparer.OrdinalIgnoreCase to the constructor to ignore case. A null item is allowed for reference types, and only one null can be stored.
Library declarations
C#
public bool Add(T item);
Parameters
Parameter
Description
item
Required. The item to add. It is stored only when no equal item is already in the set.
Return Value
Return Value
Description
bool
true if the item was added (it was new). false if the set already contained an equal item. Count goes up by 1 only for true.
C# Examples
Example 1 — Add the Same Fruit Twice
Add two fruits, then add one of them again and watch the bool results and the size of the set.
C#
using System;
using System.Collections.Generic;
class Program {
static void Main() {
HashSet<string> fruits = new HashSet<string>();
Console.WriteLine(fruits.Add("apple"));
Console.WriteLine(fruits.Add("banana"));
Console.WriteLine(fruits.Add("apple"));
Console.WriteLine(fruits.Count);
Console.WriteLine(fruits.Contains("banana"));
}
}
Output
True
True
False
2
True
How It Works
Empty start.new HashSet<string>() holds nothing yet, so the first two names are both new.
First two calls."apple" and "banana" are stored, and each call prints True.
Third call."apple" is already inside, so nothing is stored and the call prints False. No exception is thrown.
Order-free output. The program prints only Count (2 items, not 3) and a Contains answer, so it never depends on the order inside the set.
Example 2 — Add With Different Comparers
Build one set with the normal comparer and one that ignores case, then add the same name in two spellings to each.
C#
using System;
using System.Collections.Generic;
class Program {
static void Main() {
HashSet<string> exact = new HashSet<string>();
Console.WriteLine(exact.Add("Asha"));
Console.WriteLine(exact.Add("ASHA"));
Console.WriteLine(exact.Count);
HashSet<string> loose = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
Console.WriteLine(loose.Add("Asha"));
Console.WriteLine(loose.Add("ASHA"));
Console.WriteLine(loose.Count);
Console.WriteLine(loose.Contains("asha"));
}
}
Output
True
True
2
True
False
1
True
How It Works
Default comparer. A plain HashSet<string> compares strings exactly, so "Asha" and "ASHA" are two different items and both adds return True.
Two items. That is why the first Count is 2.
Custom comparer. The constructor argument StringComparer.OrdinalIgnoreCase tells the set to treat names that differ only by case as equal.
One item. The second add returns False, Count stays 1, and Contains("asha") is True because the lookup uses the same comparer.
Example 3 — Report Every Repeated Word
Walk through an array and use the result of Add to spot words that were already seen.
C#
using System;
using System.Collections.Generic;
class Program {
static void Main() {
string[] words = { "red", "blue", "red", "green", "blue", "red" };
HashSet<string> seen = new HashSet<string>();
foreach (string w in words) {
if (!seen.Add(w)) {
Console.WriteLine("Repeat: " + w);
}
}
Console.WriteLine(words.Length);
Console.WriteLine(seen.Count);
}
}
Output
Repeat: red
Repeat: blue
Repeat: red
6
3
How It Works
Loop over the array. The foreach reads the array, which keeps its order, so the messages always appear in the order the repeats happen.
Use the result.!seen.Add(w) is true only when Add returned false, which means the word was already in the set.
Three repeat messages. The second "red", the second "blue", and the third "red" are all repeats. The first time each word appears it is stored quietly.
Six in, three kept. The array has 6 words, but only the 3 distinct colours are in the set, so seen.Count is 3.
Frequently Asked Questions
It returns true if the item was new and was added, and false if the set already contained an equal item. In the false case the set does not change.
No. A duplicate is just ignored and Add returns false. This is different from Dictionary.Add, which throws ArgumentException for a repeated key.
Use UnionWith with an array or list, or pass the collection to the HashSet constructor. Both skip repeats automatically.
Yes, for a reference type such as string. Only one null can be stored, because the second null is a duplicate.
Do not depend on it. A HashSet does not promise any order. Copy the items to a List and sort it, or use SortedSet, when you need a fixed order.