Medium csharp

OOP — Encapsulation private field #36

Problem

Private balance with public Deposit method.

Hints
  • private field + public method

Your practice code

Ready — edit the code above and click Run.

Solution

using System;

class Program
{
    static void Main()
    {
        var w = new Wallet();
        w.Deposit(50);
        Console.WriteLine(w.GetBalance());

class Wallet {
    private decimal _balance;
    public void Deposit(decimal amt) => _balance += amt;
    public decimal GetBalance() => _balance;
}
    }
}

Try solving on your own first, then reveal the official answer.

Explanation

Encapsulation hides fields; expose controlled methods.

Toolliyo Assistant
Ask about tutorials, ebooks, training, pricing, mentor services, and support. I use public site content only—not admin or internal tools.

care@toolliyo.com

Need callback? Share your details