Bird
Raised Fist0

Find the mistake in this code:

medium📝 Debug Q7 of Q15
C Sharp (C#) - Collections
Find the mistake in this code:
var set = new HashSet<string>();
set.Add("cat");
set.Add("dog");
set.Remove("bird");
Console.WriteLine(set.Count);
ARemove method returns false if element not found, no error.
BHashSet cannot be declared with var keyword.
CRemoving an element not in the set causes an exception.
DAdd method cannot add string elements.
Step-by-Step Solution
Solution:
  1. Step 1: Understand Remove behavior on missing elements

    Remove returns false if element is not found but does not throw an error.
  2. Step 2: Check other options for correctness

    Var is valid, Add accepts strings, and no exception occurs on Remove.
  3. Final Answer:

    Remove method returns false if element not found, no error. -> Option A
  4. Quick Check:

    HashSet Remove missing element = returns false [OK]
Quick Trick: Remove returns false if element absent, no exception thrown [OK]
Common Mistakes:
MISTAKES
  • Expecting exception on removing missing element
  • Thinking var cannot declare HashSet
  • Believing Add rejects strings

Want More Practice?

15+ quiz questions · All difficulty levels · Free

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