Bird
0
0

Identify the issue in this property setter:

medium📝 Debug Q6 of 15
C Sharp (C#) - Properties and Encapsulation
Identify the issue in this property setter:
private int _score;
public int Score {
  get { return _score; }
  set {
    if (value < 0) throw new ArgumentOutOfRangeException("Score cannot be negative");
    _score = value;
    _score = value;
  }
}
AThe setter assigns the value to the backing field twice unnecessarily
BThe exception type is incorrect for negative values
CThe getter should also validate the value
DThe backing field should be public instead of private
Step-by-Step Solution
Solution:
  1. Step 1: Review setter code

    The setter assigns '_score = value;' two times consecutively.
  2. Step 2: Understand implications

    Assigning twice is redundant and unnecessary, but not harmful.
  3. Step 3: Check other options

    ArgumentOutOfRangeException is appropriate for negative values; getter does not require validation; backing field should be private.
  4. Final Answer:

    The setter assigns the value to the backing field twice unnecessarily -> Option A
  5. Quick Check:

    Duplicate assignment is redundant [OK]
Quick Trick: Avoid redundant assignments in setters [OK]
Common Mistakes:
MISTAKES
  • Confusing exception types
  • Adding validation in getter
  • Making backing fields public

Want More Practice?

15+ quiz questions · All difficulty levels · Free

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