0
0
C Sharp (C#)programming~30 mins

Why encapsulation matters in C Sharp (C#) - See It in Action

Choose your learning style9 modes available
Why encapsulation matters
📖 Scenario: Imagine you are building a simple bank account system. You want to keep the account balance safe so no one can change it directly by mistake. This is where encapsulation helps.
🎯 Goal: You will create a BankAccount class that keeps the balance private. You will add methods to safely deposit and withdraw money. Finally, you will show the balance using a method.
📋 What You'll Learn
Create a class called BankAccount with a private field balance of type decimal
Add a public method Deposit that adds money to balance
Add a public method Withdraw that subtracts money from balance only if there is enough money
Add a public method GetBalance that returns the current balance
Create an instance of BankAccount and use the methods to deposit, withdraw, and print the balance
💡 Why This Matters
🌍 Real World
Encapsulation is used in real bank software to protect account balances and prevent errors or fraud.
💼 Career
Understanding encapsulation is essential for writing safe and maintainable code in any software development job.
Progress0 / 4 steps
1
Create the BankAccount class with a private balance
Create a class called BankAccount with a private field balance of type decimal and set it to 0.
C Sharp (C#)
Need a hint?

Use private decimal balance = 0m; inside the class.

2
Add Deposit and Withdraw methods
Add a public method Deposit that takes a decimal amount and adds it to balance. Add a public method Withdraw that takes a decimal amount and subtracts it from balance only if balance is greater or equal to amount.
C Sharp (C#)
Need a hint?

Use public void Deposit(decimal amount) and public void Withdraw(decimal amount) methods with the described logic.

3
Add GetBalance method
Add a public method GetBalance that returns the current balance as decimal.
C Sharp (C#)
Need a hint?

Use public decimal GetBalance() method that returns balance.

4
Create BankAccount instance and use methods
Create an instance of BankAccount called account. Deposit 100.50, withdraw 20.25, then print the balance using Console.WriteLine and account.GetBalance().
C Sharp (C#)
Need a hint?

Create BankAccount account = new BankAccount();, then call Deposit(100.50m), Withdraw(20.25m), and print balance with Console.WriteLine(account.GetBalance());.