Bird
Raised Fist0
C Sharp (C#)programming~10 mins

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

Choose your learning style10 modes available
Concept Flow - HashSet for unique elements
Create empty HashSet
↓
Add element?
No→Skip add
Yes↓
Element added if unique
↓
More elements?
No→End
↩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.

Practice

(1/5)
1. What is the main purpose of using a HashSet<T> in C#?
easy
A. To allow duplicate elements for faster access
B. To store elements in sorted order
C. To store unique elements without duplicates
D. To store key-value pairs like a dictionary

Solution

  1. Step 1: Understand HashSet behavior

    A HashSet automatically ignores duplicate entries and stores only unique elements.
  2. Step 2: Compare with other collections

    Unlike lists or dictionaries, HashSet does not allow duplicates and does not maintain order.
  3. Final Answer:

    To store unique elements without duplicates -> Option C
  4. Quick Check:

    HashSet = Unique elements [OK]
Hint: HashSet always keeps unique items only [OK]
Common Mistakes:
  • Thinking HashSet keeps elements sorted
  • Assuming HashSet allows duplicates
  • Confusing HashSet with Dictionary
2. Which of the following is the correct way to declare and initialize a HashSet<int> with values 1, 2, and 3?
easy
A. var set = HashSet<int> = {1, 2, 3};
B. var set = new HashSet<int> {1, 2, 3};
C. var set = new HashSet<int>[1, 2, 3];
D. var set = new HashSet<int>(1, 2, 3);

Solution

  1. Step 1: Check HashSet initialization syntax

    HashSet can be initialized with collection initializer syntax using curly braces after the constructor.
  2. Step 2: Validate each option

    var set = new HashSet<int> {1, 2, 3}; uses correct syntax: new HashSet<int> {1, 2, 3}; Options A, B, and C have invalid syntax.
  3. Final Answer:

    var set = new HashSet<int> {1, 2, 3}; -> Option B
  4. Quick Check:

    Use curly braces after constructor for initialization [OK]
Hint: Use curly braces after new HashSet for values [OK]
Common Mistakes:
  • Using parentheses with multiple values directly
  • Trying to declare array instead of HashSet
  • Incorrect assignment syntax
3. What will be the output of the following C# code?
var set = new HashSet<string>();
set.Add("apple");
set.Add("banana");
set.Add("apple");
Console.WriteLine(set.Count);
medium
A. 0
B. 3
C. 1
D. 2

Solution

  1. Step 1: Add elements to HashSet

    "apple" is added first, then "banana", then "apple" again.
  2. Step 2: Understand duplicate handling

    The second "apple" is ignored because HashSet stores unique elements only.
  3. Final Answer:

    2 -> Option D
  4. Quick Check:

    Duplicates ignored, count = 2 [OK]
Hint: Count equals unique items added, duplicates ignored [OK]
Common Mistakes:
  • Counting duplicates as separate elements
  • Assuming HashSet allows duplicates
  • Confusing Count with number of Add calls
4. Identify the error in this code snippet using HashSet<int>:
HashSet<int> numbers = new HashSet<int>();
numbers.Add(1);
numbers.Add(2);
numbers.Add(1);
Console.WriteLine(numbers[0]);
medium
A. HashSet does not support indexing with []
B. Cannot add duplicate values to HashSet
C. HashSet must be initialized with values
D. Add method returns void, cannot be used like this

Solution

  1. Step 1: Review HashSet usage

    HashSet stores unique elements but does not support accessing elements by index.
  2. Step 2: Identify invalid operation

    Using numbers[0] causes a compile-time error because HashSet has no indexer.
  3. Final Answer:

    HashSet does not support indexing with [] -> Option A
  4. Quick Check:

    No index access on HashSet [OK]
Hint: HashSet has no indexer; use foreach or Contains [OK]
Common Mistakes:
  • Trying to access elements by index
  • Thinking Add returns a value
  • Assuming duplicates cause errors
5. You have a list of integers with duplicates: List<int> nums = new List<int> {1, 2, 2, 3, 4, 4, 4, 5};
Which code snippet correctly creates a HashSet<int> containing only the unique elements from nums?
hard
A. var unique = new HashSet<int>(nums);
B. var unique = new HashSet<int>(); unique.Add(nums);
C. var unique = new HashSet<int>(); foreach(var n in nums) unique = n;
D. var unique = new HashSet<int>(); unique.AddRange(nums);

Solution

  1. Step 1: Understand HashSet constructor

    HashSet has a constructor that accepts an IEnumerable<T> to initialize with unique elements.
  2. Step 2: Analyze each option

    var unique = new HashSet<int>(nums); correctly passes the list to the constructor. var unique = new HashSet<int>(); unique.Add(nums); tries to add the whole list as one item (invalid). var unique = new HashSet<int>(); foreach(var n in nums) unique = n; assigns int to HashSet variable (invalid). var unique = new HashSet<int>(); unique.AddRange(nums); uses AddRange which HashSet does not have.
  3. Final Answer:

    var unique = new HashSet<int>(nums); -> Option A
  4. Quick Check:

    Use constructor with collection for unique set [OK]
Hint: Pass list to HashSet constructor for unique items [OK]
Common Mistakes:
  • Using Add to add whole list at once
  • Trying to assign int to HashSet variable
  • Using AddRange which HashSet lacks
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard