Menu
Coddy logo textTech

What is a HashSet?

Part of the Logic & Flow section of Coddy's C# journey — lesson 56 of 66.

A HashSet is a collection in C# that stores unique elements in no particular order. It's part of the System.Collections.Generic namespace and provides high-performance set operations.

First, include the required namespace:

using System.Collections.Generic;

Create an empty HashSet:

HashSet<string> fruits = new HashSet<string>();

This creates a HashSet that can store string values.

Unlike arrays or lists, HashSets:

  • Don't allow duplicate elements
  • Don't maintain insertion order
  • Provide fast lookup operations (O(1) complexity)
  • Are ideal for when you need to ensure uniqueness

If you try to add a duplicate element, the HashSet will ignore it:

fruits.Add("Apple");
fruits.Add("Apple"); // This is ignored

After executing the above code, the set still contains only one "Apple".

Cheat sheet

A HashSet is a collection that stores unique elements with no particular order and provides fast lookup operations.

Include the required namespace:

using System.Collections.Generic;

Create a HashSet:

HashSet<string> fruits = new HashSet<string>();

Key characteristics:

  • No duplicate elements allowed
  • No insertion order maintained
  • Fast lookup operations (O(1) complexity)
  • Duplicate additions are ignored

Adding elements:

fruits.Add("Apple");
fruits.Add("Apple"); // Ignored - no duplicates

Try it yourself

This lesson doesn't include a code challenge.

quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Logic & Flow