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 ignoredAfter 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 duplicatesTry it yourself
This lesson doesn't include a code challenge.
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Logic & Flow
1Multi-dimensional Arrays
2D Arrays BasicsDeclaring and Initializing 2DAccessing 2D Array ElementsNested Loops with 2D ArraysJagged ArraysCommon Matrix OperationsRecap - Multi-dimensional4Flow Control Techniques
Early ReturnsGuard ClausesJump Statements (goto)Break and ContinueFlatten Nested Conditionals7Logical Operators Advanced
Short-Circuit EvaluationConditional Logical OperatorsOperator PrecedenceRecap - Advanced Operators2Advanced Decision Making
Multiple ConditionsComplex Boolean LogicIf vs. Switch ComparisonNested Switch StatementsRecap - Advanced Decisions5Exception Handling
Try-Catch BasicsException TypesMultiple Catch BlocksWorking with FilesFinally BlockUsing vs. Try-FinallyCustom ExceptionsRecap - Error Handling8Data Analysis System
Data Collection SetupData Entry Logic11HashSet Part 1
What is a HashSet?Adding an ElementRemoving an ElementChecking if an Element ExistsEmpty and SizeRecap - HashSet3Loop Enhancements
Loop PerformanceIterating ComplexEach Loop TypeRefactoring LoopsRecap - Optimized Loops6Null Handling
Null Reference BasicsNullable Value TypesNull Checking PatternsDefensive ProgrammingRecap - Null Safety