Bird
0
0

What will be the output of this C# code?

medium📝 Predict Output Q4 of 15
C Sharp (C#) - Collections
What will be the output of this C# code?
var set = new HashSet<int>() {1, 2, 3};
set.Add(2);
Console.WriteLine(set.Count);
A3
B4
C2
DRuntime error
Step-by-Step Solution
Solution:
  1. Step 1: Initialize HashSet with 3 unique elements

    The set starts with elements 1, 2, and 3, so count is 3.
  2. Step 2: Add duplicate element 2 and check count

    Adding 2 again is ignored, so count remains 3.
  3. Final Answer:

    3 -> Option A
  4. Quick Check:

    HashSet count after duplicate add = 3 [OK]
Quick Trick: Adding duplicates does not increase HashSet count [OK]
Common Mistakes:
MISTAKES
  • Assuming count increases on duplicate add
  • Expecting runtime error on duplicate add
  • Confusing initial count with added elements

Want More Practice?

15+ quiz questions · All difficulty levels · Free

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