How to Use HashSet in C#: Syntax, Example, and Tips
In C#, use
HashSet<T> to store unique elements without duplicates. You create a HashSet, add items with Add(), and check membership with Contains().Syntax
The HashSet<T> class stores unique elements of type T. You create it with new HashSet<T>(). Use Add(item) to add elements, Remove(item) to delete, and Contains(item) to check if an element exists.
csharp
HashSet<string> set = new HashSet<string>(); set.Add("apple"); bool hasApple = set.Contains("apple"); set.Remove("apple");
Example
This example shows how to create a HashSet, add items, check for duplicates, and print all unique items.
csharp
using System; using System.Collections.Generic; class Program { static void Main() { HashSet<string> fruits = new HashSet<string>(); fruits.Add("apple"); fruits.Add("banana"); fruits.Add("apple"); // duplicate, will not be added Console.WriteLine("Fruits in the set:"); foreach (var fruit in fruits) { Console.WriteLine(fruit); } Console.WriteLine($"Contains 'banana'? {fruits.Contains("banana")}"); } }
Output
Fruits in the set:
apple
banana
Contains 'banana'? True
Common Pitfalls
Common mistakes include trying to add duplicates (which HashSet ignores silently) and expecting ordered items (HashSet does not keep order). Also, modifying a set while iterating causes errors.
csharp
/* Wrong: Adding duplicates has no effect */ HashSet<int> numbers = new HashSet<int>(); numbers.Add(1); numbers.Add(1); // ignored, no error but no duplicate added /* Wrong: Modifying during foreach causes error */ // foreach (var n in numbers) { // numbers.Add(2); // throws InvalidOperationException // } /* Right: Collect items to add, then add after loop */ var toAdd = new List<int> { 2 }; foreach (var n in numbers) { // do something } foreach (var n in toAdd) { numbers.Add(n); }
Quick Reference
- Create:
new HashSet<T>() - Add:
Add(item) - Remove:
Remove(item) - Check:
Contains(item) - Count:
Countproperty - Clear all:
Clear()
Key Takeaways
HashSet stores unique elements and ignores duplicates automatically.
Use Add, Remove, and Contains methods to manage items in the set.
HashSet does not maintain order of elements.
Avoid modifying a HashSet while iterating over it to prevent errors.
HashSet is efficient for fast lookups and uniqueness checks.