0
0
C Sharp (C#)programming~10 mins

HashSet for unique elements in C Sharp (C#) - Step-by-Step Execution

Choose your learning style9 modes available
Concept Flow - HashSet for unique elements
Create empty HashSet
Add element?
NoSkip add
Yes
Element added if unique
More elements?
NoEnd
Back to Add element?
Start with an empty HashSet, try to add elements one by one. Only unique elements get added. Repeat until no more elements.
Execution Sample
C Sharp (C#)
var set = new HashSet<int>();
set.Add(1);
set.Add(2);
set.Add(1);
Console.WriteLine(set.Count);
Adds numbers to a HashSet and prints how many unique numbers are inside.
Execution Table
StepActionElement AddedSet ContentsOutput
1Create empty HashSetN/A{}
2Add 11{1}
3Add 22{1, 2}
4Add 1 againNo (duplicate){1, 2}
5Print CountN/A{1, 2}2
💡 All elements processed; duplicates ignored; final count is 2
Variable Tracker
VariableStartAfter Step 2After Step 3After Step 4Final
set{}{1}{1, 2}{1, 2}{1, 2}
Key Moments - 2 Insights
Why doesn't adding '1' the second time change the set?
Because HashSet only keeps unique elements. Step 4 in the execution_table shows 'Add 1 again' is ignored since '1' is already inside.
What does set.Count represent?
It shows how many unique elements are in the set. Step 5 prints '2' because only two unique numbers (1 and 2) were added.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution_table, what is the set content after step 3?
A{}
B{1, 2}
C{1}
D{2}
💡 Hint
Check the 'Set Contents' column at step 3 in the execution_table.
At which step is a duplicate element detected and not added?
AStep 4
BStep 2
CStep 3
DStep 5
💡 Hint
Look for 'No (duplicate)' in the 'Element Added' column in the execution_table.
If we add '3' after step 4, what will be the new count?
A4
B2
C3
D1
💡 Hint
Adding a new unique element increases the count by 1; see variable_tracker for how set changes.
Concept Snapshot
HashSet stores unique elements only.
Use Add() to insert elements; duplicates are ignored.
Count property shows number of unique items.
Ideal for removing duplicates quickly.
Full Transcript
This example shows how a HashSet in C# keeps only unique elements. We start with an empty set. Adding '1' puts it inside. Adding '2' adds another unique element. Trying to add '1' again does nothing because it's a duplicate. Finally, printing Count shows 2, the number of unique elements. HashSet is useful when you want to avoid duplicates automatically.