Consider the following C# code using HashSet<int>. What will be printed?
using System; using System.Collections.Generic; class Program { static void Main() { HashSet<int> numbers = new HashSet<int>() {1, 2, 3, 2, 4, 1}; Console.WriteLine(numbers.Count); } }
HashSet stores only unique elements. Duplicate values are ignored.
The HashSet contains unique elements: 1, 2, 3, 4. Duplicates like the second 1 and 2 are ignored. So the count is 4.
What will be the output of this C# program?
using System; using System.Collections.Generic; class Program { static void Main() { HashSet<string> fruits = new HashSet<string>(); fruits.Add("apple"); fruits.Add("banana"); fruits.Add("apple"); fruits.Add("orange"); Console.WriteLine(fruits.Count); } }
HashSet ignores duplicates when adding.
"apple" is added twice but only stored once. The unique fruits are "apple", "banana", and "orange". Count is 3.
Examine the code below. It throws a runtime exception. What is the cause?
using System; using System.Collections.Generic; class Program { static void Main() { HashSet<int> set = new HashSet<int>() {1, 2, 3}; foreach (var item in set) { if (item == 2) { set.Remove(item); } } } }
Think about what happens if you change a collection while looping over it.
Removing items from a HashSet during foreach iteration causes an InvalidOperationException because the collection is modified during enumeration.
What will this program print?
using System; using System.Collections.Generic; class Program { static void Main() { HashSet<int> setA = new HashSet<int>() {1, 2, 3, 4}; HashSet<int> setB = new HashSet<int>() {3, 4, 5, 6}; setA.IntersectWith(setB); Console.WriteLine(string.Join(",", setA)); } }
IntersectWith keeps only elements present in both sets.
After intersection, setA contains only elements common to setA and setB: 3 and 4.
Which statement best describes the average time complexity of Add, Remove, and Contains operations in a C# HashSet<T>?
Think about how hashing helps find elements quickly.
HashSet uses a hash table internally, so Add, Remove, and Contains usually run in constant time O(1) on average.