Bird
0
0

You want to ensure a class property Age can only be set to values between 0 and 120. Which encapsulation technique is best in C#?

hard🚀 Application Q8 of 15
C Sharp (C#) - Properties and Encapsulation
You want to ensure a class property Age can only be set to values between 0 and 120. Which encapsulation technique is best in C#?
AUse a public field and rely on user discipline
BMake the field public and check values before assignment externally
CUse a private field with a public property that validates values in the setter
DDeclare the field as protected without validation
Step-by-Step Solution
Solution:
  1. Step 1: Understand encapsulation for validation

    Encapsulation allows controlling how data is accessed and modified.
  2. Step 2: Choose approach that enforces constraints

    A private field with a public property setter that validates input ensures only valid values are assigned.
  3. Final Answer:

    Use a private field with a public property that validates values in the setter -> Option C
  4. Quick Check:

    Properties with validation enforce data integrity [OK]
Quick Trick: Validate data in property setters [OK]
Common Mistakes:
MISTAKES
  • Making fields public and trusting external checks
  • Not validating data before assignment
  • Using protected without validation

Want More Practice?

15+ quiz questions · All difficulty levels · Free

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