← C# from Scratch
Lesson 30 of 39 · 10 XP
Access modifiers
Theory and problem statement
Machine translation, not yet reviewed by a native speaker.
Who can access a field or a method:
| modifier | access |
|---|---|
public |
from anywhere |
private |
only inside its own class — the default for class members |
protected |
its own class and subclasses |
internal |
the whole assembly (project) — the default for classes |
Why hide things? So that the object guards its own rules:
class Wallet
{
private int coins; // can't be changed directly from outside
public bool Spend(int n)
{
if (n <= 0 || n > coins) return false; // the rule: you can't go below zero
coins -= n;
return true;
}
}
w.coins = -100; // error CS0122: 'coins' is inaccessible due to its protection level
That's encapsulation: the field is private, and you work with it through public methods with checks.
Task. Finish BankAccount with a private balance field: Deposit(int) (positive amounts),
bool Withdraw(int) (not more than the balance and not ≤ 0) and int GetBalance(). The program runs
the commands dep N, wd N, prints ok/denied for each withdrawal, and the balance at the end.
Sign up for free to solve this task right in your browser: code editor, running, test checks and hints.