HashSet and Uniqueness
Track distinct values.
HashSet and Uniqueness is a free C# Academy lesson on CoddyKit — lesson 3 of 4. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the C# Academy learning path, one of 4 lessons in the course, and your progress syncs across the web and the CoddyKit app.
What Is a HashSet?
HashSet<T> stores a collection of unique values with no duplicates. Adding a value already present simply does nothing.
Like a dictionary, it is backed by a hash table, so membership tests are average O(1). It does not keep insertion order.
using System.Collections.Generic;
var seen = new HashSet<int>();
seen.Add(1);
seen.Add(1); // ignored, still one elementAdd Returns a Bool
Add returns true if the value was new and false if it was already present.
That return value is useful for detecting duplicates in one step, without a separate Contains check.
using System;
using System.Collections.Generic;
class Program {
static void Main() {
var set = new HashSet<string>();
Console.WriteLine(set.Add("a")); // True
Console.WriteLine(set.Add("a")); // False
}
}Fast Membership Tests
Contains on a HashSet is average O(1), compared with O(n) on a List.
When you repeatedly ask "have I seen this?", a set is the right tool. The speed difference grows dramatically as the collection gets large.
using System;
using System.Collections.Generic;
class Program {
static void Main() {
var ids = new HashSet<int> { 10, 20, 30 };
Console.WriteLine(ids.Contains(20)); // True
Console.WriteLine(ids.Contains(99)); // False
}
}Removing Duplicates from a List
A common task: take a list and keep only distinct values. Constructing a HashSet from the list does this in O(n).
The resulting set has each value once. If you need a list back, wrap it: new List<int>(set).
using System;
using System.Collections.Generic;
class Program {
static void Main() {
var nums = new List<int> { 1, 2, 2, 3, 3, 3 };
var unique = new HashSet<int>(nums);
Console.WriteLine(unique.Count); // 3
}
}Union
UnionWith adds every element of another collection, skipping duplicates. The result holds everything from both.
This mutates the set in place. It is far cleaner than looping and calling Add for each item yourself.
using System;
using System.Collections.Generic;
class Program {
static void Main() {
var a = new HashSet<int> { 1, 2, 3 };
a.UnionWith(new[] { 3, 4, 5 });
Console.WriteLine(a.Count); // 5
}
}Intersection
IntersectWith keeps only the elements that also appear in the other collection, dropping the rest.
Use it to find common items, such as tags shared by two articles or users in both of two groups.
using System;
using System.Collections.Generic;
class Program {
static void Main() {
var a = new HashSet<int> { 1, 2, 3, 4 };
a.IntersectWith(new[] { 2, 4, 6 });
Console.WriteLine(string.Join(",", a)); // 2,4
}
}Difference
ExceptWith removes from the set any element found in the other collection, leaving what is unique to the set.
It is the set-minus operation: "items in A but not in B". Great for computing what changed or what is left to process.
var a = new HashSet<int> { 1, 2, 3, 4 };
a.ExceptWith(new[] { 2, 4 });
// a now contains 1 and 3Subset and Superset
IsSubsetOf and IsSupersetOf test containment relationships between sets, returning a bool.
Overlaps checks if any element is shared, and SetEquals tests if two sets hold exactly the same elements regardless of order.
var a = new HashSet<int> { 1, 2 };
var b = new HashSet<int> { 1, 2, 3 };
bool sub = a.IsSubsetOf(b); // true
bool ov = a.Overlaps(b); // trueElement Equality
Uniqueness depends on GetHashCode and Equals of the element type, exactly like dictionary keys.
For custom types, override both or use a record, otherwise two logically equal objects are treated as distinct and both end up in the set.
var names = new HashSet<string>(
System.StringComparer.OrdinalIgnoreCase);
names.Add("Sam");
bool dup = !names.Add("SAM"); // true: treated as sameNo Indexing or Order
A HashSet has no index access; you cannot write set[0]. You can only enumerate it with foreach.
Enumeration order is not guaranteed. If you need both uniqueness and sorted order, use SortedSet<T>, which keeps elements ordered at the cost of O(log n) operations.
using System;
using System.Collections.Generic;
class Program {
static void Main() {
var s = new SortedSet<int> { 3, 1, 2 };
Console.WriteLine(string.Join(",", s)); // 1,2,3
}
}Tracking Seen Items
A frequent pattern is filtering a stream so each value appears once. Add to a set and act only when Add returns true.
This is cleaner and faster than checking a growing list, turning an O(n squared) scan into O(n).
using System;
using System.Collections.Generic;
class Program {
static void Main() {
var seen = new HashSet<int>();
foreach (int x in new[] { 1, 1, 2, 3, 2 })
if (seen.Add(x)) Console.Write(x + " ");
// prints 1 2 3
}
}Quick Check
Recall what a HashSet enforces and its lookup cost.
Recap
HashSet<T> stores unique values with average O(1) add, remove, and membership tests, but no order or indexing.
It shines for deduplication, fast "have I seen this" checks, and set algebra via UnionWith, IntersectWith, and ExceptWith. Custom element types need proper equality.
Frequently asked questions
Is the “HashSet and Uniqueness” lesson free?
Yes — the full text of “HashSet and Uniqueness” is free to read here on the web, and the C# Academy course includes 4 lessons in total. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the C# Academy course, upgrade to CoddyKit PRO.
What will I learn in “HashSet and Uniqueness”?
Track distinct values. You practise C# Academy with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.
Do I need any experience to start C# Academy?
No prior experience is required. C# Academy on CoddyKit is structured for beginners through advanced learners; this is — lesson 3 of 4, so you can start here or from the beginning and move at your own pace.
How long does the “HashSet and Uniqueness” lesson take?
Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.
Can I write and run code in this C# Academy lesson?
Yes. Every C# Academy lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.
All lessons in this course
- List in Practice
- Dictionary Lookups
- HashSet and Uniqueness
- Choosing a Collection