Bird
0
0

What will be the output of the following C# code?

medium📝 Predict Output Q5 of 15
C Sharp (C#) - Collections
What will be the output of the following C# code?
var fruits = new HashSet<string>();
fruits.Add("orange");
fruits.Add("grape");
fruits.Add("orange");
Console.WriteLine(fruits.Count);
A3
B2
C1
D0
Step-by-Step Solution
Solution:
  1. Step 1: Add "orange" to the HashSet

    The set now contains {"orange"}.
  2. Step 2: Add "grape" to the HashSet

    The set now contains {"orange", "grape"}.
  3. Step 3: Attempt to add "orange" again

    Since "orange" is already in the set, it will not be added again.
  4. Final Answer:

    2 -> Option B
  5. Quick Check:

    HashSet stores unique elements only. [OK]
Quick Trick: HashSet ignores duplicates, count unique items only [OK]
Common Mistakes:
MISTAKES
  • Assuming duplicates increase count
  • Confusing List behavior with HashSet
  • Thinking Add always adds element

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More C Sharp (C#) Quizzes