Bird
Raised Fist0

You want to create a class BankAccount where the Balance can be read publicly but only changed inside the class. Which is the best way to declare Balance?

hard🚀 Application Q15 of Q15
C Sharp (C#) - Properties and Encapsulation
You want to create a class BankAccount where the Balance can be read publicly but only changed inside the class. Which is the best way to declare Balance?
Apublic decimal Balance; // public field
Bprivate decimal balance; public decimal Balance { get; private set; }
Cpublic decimal Balance { private get; set; }
Dprivate decimal Balance; public decimal balance { get; set; }
Step-by-Step Solution
Solution:
  1. Step 1: Understand access needs

    Balance should be readable publicly but only settable privately inside the class.
  2. Step 2: Choose property with private set

    Using public decimal Balance { get; private set; } allows public reading but restricts setting to inside the class.
  3. Final Answer:

    private decimal balance; public decimal Balance { get; private set; } -> Option B
  4. Quick Check:

    Public get + private set = controlled access [OK]
Quick Trick: Use property with private set for controlled write access. [OK]
Common Mistakes:
MISTAKES
  • Using public field exposes data to unwanted changes.
  • Setting private get hides data from outside.
  • Confusing field and property naming conventions.

Want More Practice?

15+ quiz questions · All difficulty levels · Free

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