Bird
Raised Fist0

You want to create a property Age that only allows values between 0 and 120. Which implementation correctly enforces this using get and set accessors?

hard🚀 Application Q15 of Q15
C Sharp (C#) - Properties and Encapsulation
You want to create a property Age that only allows values between 0 and 120. Which implementation correctly enforces this using get and set accessors?
Aprivate int age; public int Age { get { return age; } set { if (value >= 0 && value <= 120) age = value; } }
Bpublic int Age { get; set; } // No validation needed
Cprivate int age; public int Age { get { return age; } set { age = value; } }
Dprivate int age; public int Age { get { return age; } set { if (value > 0) age = value; } }
Step-by-Step Solution
Solution:
  1. Step 1: Check validation logic in set accessor

    private int age; public int Age { get { return age; } set { if (value >= 0 && value <= 120) age = value; } } checks if value is between 0 and 120 before assigning it to the private field.
  2. Step 2: Compare other options

    The auto-implemented property has no validation. The simple backing field assignment lacks checks. The partial validation only checks if value > 0, missing the upper limit.
  3. Final Answer:

    private int age; public int Age { get { return age; } set { if (value >= 0 && value <= 120) age = value; } } -> Option A
  4. Quick Check:

    Set accessor validates range 0-120 = B [OK]
Quick Trick: Use if condition in set to validate value range [OK]
Common Mistakes:
MISTAKES
  • Not validating upper limit
  • Assigning value without checks
  • Assuming auto-properties validate automatically

Want More Practice?

15+ quiz questions · All difficulty levels · Free

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