Bird
Raised Fist0

You want to create a property Score that only allows values between 0 and 100. Which is the best way to implement the set accessor?

hard🚀 Application Q8 of Q15
C Sharp (C#) - Properties and Encapsulation
You want to create a property Score that only allows values between 0 and 100. Which is the best way to implement the set accessor?
AUse <code>set { score = 100; }</code> always
BUse <code>set { score = value; }</code> without checks
CUse <code>get { return score; }</code> only, no set
DUse <code>set { if(value >= 0 && value <= 100) score = value; }</code>
Step-by-Step Solution
Solution:
  1. Step 1: Understand validation in set accessor

    To restrict values, add a condition inside set to check the value range.
  2. Step 2: Choose correct conditional assignment

    Use set { if(value >= 0 && value <= 100) score = value; } uses an if statement to assign only valid values between 0 and 100.
  3. Final Answer:

    Use set { if(value >= 0 && value <= 100) score = value; } -> Option D
  4. Quick Check:

    Validate values inside set accessor [OK]
Quick Trick: Validate input inside set accessor [OK]
Common Mistakes:
MISTAKES
  • Not validating values
  • Using get only to restrict
  • Assigning fixed value always

Want More Practice?

15+ quiz questions · All difficulty levels · Free

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