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
Step 1: Review HashSet usage
HashSet stores unique elements but does not support accessing elements by index.
Step 2: Identify invalid operation
Using numbers[0] causes a compile-time error because HashSet has no indexer.
Final Answer:
HashSet does not support indexing with [] -> Option A
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
Step 1: Understand HashSet constructor
HashSet has a constructor that accepts an IEnumerable<T> to initialize with unique elements.
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.
Final Answer:
var unique = new HashSet<int>(nums); -> Option A
Quick Check:
Use constructor with collection for unique set [OK]
Hint: Pass list to HashSet constructor for unique items [OK]