Bird
0
0

Examine the code below:

medium📝 Debug Q7 of 15
C Sharp (C#) - Properties and Encapsulation
Examine the code below:
class Wallet {
  private decimal amount;
  public void SetAmount(decimal value) {
    amount = value;
  }
}
class Program {
  static void Main() {
    Wallet w = new Wallet();
    w.amount = 500m;
  }
}

What is the main problem with this code?
ADecimal type cannot be used for amount
BMethod SetAmount has wrong parameter type
CClass Wallet should be static
DCannot access private field 'amount' directly outside the class
Step-by-Step Solution
Solution:
  1. Step 1: Identify access modifiers

    The field amount is declared private, so it cannot be accessed outside Wallet.
  2. Step 2: Check usage in Main()

    Attempting w.amount = 500m; violates encapsulation and causes a compile error.
  3. Final Answer:

    Cannot access private field 'amount' directly outside the class -> Option D
  4. Quick Check:

    Private fields are inaccessible outside their class [OK]
Quick Trick: Private fields inaccessible outside class [OK]
Common Mistakes:
MISTAKES
  • Assuming private fields can be accessed directly
  • Confusing method parameter types
  • Thinking class must be static

Want More Practice?

15+ quiz questions · All difficulty levels · Free

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