Bird
0
0

You want to protect a class field so it can only be set to positive values. Which encapsulation approach is best in C#?

hard🚀 Application Q15 of 15
C Sharp (C#) - Properties and Encapsulation
You want to protect a class field so it can only be set to positive values. Which encapsulation approach is best in C#?
AMake the field protected and allow subclasses to set any value
BMake the field public and check values outside the class
CMake the field private and provide a public getter only
DMake the field private and provide a public setter method that validates the value
Step-by-Step Solution
Solution:
  1. Step 1: Understand the need for validation

    To ensure only positive values are set, validation must happen inside the class.
  2. Step 2: Choose encapsulation method

    Making the field private and using a public setter method with validation allows control over allowed values.
  3. Final Answer:

    Make the field private and provide a public setter method that validates the value -> Option D
  4. Quick Check:

    Private field + validated setter = safe data [OK]
Quick Trick: Use private field with validated public setter method [OK]
Common Mistakes:
MISTAKES
  • Making field public and trusting external code
  • Providing only a getter without setter
  • Using protected without validation

Want More Practice?

15+ quiz questions · All difficulty levels · Free

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