Bird
0
0

Identify the error in this property setter code:

medium📝 Debug Q14 of 15
C Sharp (C#) - Properties and Encapsulation
Identify the error in this property setter code:
private string name;
public string Name {
  get { return name; }
  set {
    if (value == null || value == "")
      throw new ArgumentException("Name cannot be empty");
    name = value;
  }
}
AThe setter does not assign the value to the field
BThe setter should use 'value.Equals("")' instead of 'value == ""'
CThe setter does not check for whitespace-only strings
DThe setter should not throw exceptions in property setters
Step-by-Step Solution
Solution:
  1. Step 1: Review validation logic

    The setter checks if value is null or empty string but does not check if value is whitespace only.
  2. Step 2: Understand missing validation

    Strings like " " (spaces) pass the check but are usually invalid for a name.
  3. Final Answer:

    The setter does not check for whitespace-only strings -> Option C
  4. Quick Check:

    Missing whitespace check in setter validation [OK]
Quick Trick: Check for whitespace with string.IsNullOrWhiteSpace [OK]
Common Mistakes:
MISTAKES
  • Thinking '==' is wrong for string comparison here
  • Believing exceptions should never be thrown in setters
  • Forgetting to assign value to field

Want More Practice?

15+ quiz questions · All difficulty levels · Free

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