0

C#: Access modifiers code errors and encapsulation.

Here is the example that was given in C# course on encapsulation. class BankAccount { private double balance=0; public void Deposit(double n) { balance += n; } public void Withdraw(double n) { balance -= n; } public double GetBalance() { return balance; } } class Program { static void Main(string[] args) { BankAccount b = new BankAccount(); b.Deposit(199); b.Withdraw(42); Console.WriteLine(b.GetBalance()); } I decided to play with it and changed it like this: class BankAccount { public double balance=0; public void Deposit(double n) { balance += n; } public void Withdraw(double n) { balance -= n; } public double GetBalance() { return balance; } } class Program { static void Main(string[] args) { BankAccount b = new BankAccount(); b.Deposit(199); b.Withdraw(42); balance.Deposit(100); Console.WriteLine(b.GetBalance()); } The error appeared, that balance does not exist in this context. Why? I thought changing the access modifier from private to public will make me able to access this variable.

15th Feb 2022, 6:32 AM
Юля Гуртовенко
Юля Гуртовенко - avatar
2 Respuestas
+ 2
The line balance.Deposit(100); Here is the problem. <balance> is not defined in Main() method, <balance> is defined as member of BankAccount class. And there, it was defined as `double` type. In Main() method you treat <balance> as if it was a BankAccount instance (calling Deposit() method). Perhaps you meant this? b.Deposit(100);
15th Feb 2022, 6:43 AM
Ipang
+ 3
In addition, making balance public means you can access it directly without going through Deposit of Withdraw. For example: b.balance = 0; would work in your version but not in the original because it is private there. But to access balance, you need an object (b) to reference it (b.balance).
15th Feb 2022, 6:56 AM
Ani Jona 🕊
Ani Jona 🕊 - avatar