Access Modifiers in C#: public, private, protected, internal — what is the difference and when to use what?
Hello everyone! I just started learning C# and writing my first classes. I stumbled upon access modifiers. I kind of understand that `public` is "for everyone", `private` is "only inside the class", and `protected` is "for inheritors". But in practice, I get confused.
Here is an example. I have a class `BankAccount`:
class BankAccount
{
public string AccountNumber { get; set; }
private decimal balance = 0;
protected decimal interestRate = 0.05m;
public void Deposit(decimal amount)
{
balance += amount;
}
}
Then I create a class `SavingsAccount` that inherits from `BankAccount`:
class SavingsAccount : BankAccount
{
public void ApplyInterest()
{
// Here is the problem: I can use interestRate (protected),
// but I cannot use balance (private).
// This is clear. But what if I want to give access to balance
// only to inheritors, but not to everyone else? No answers yet.
Log in to leave an answer