C#
Summary - Encapsulation
Combine access modifiers, properties and init to write an Account class.
Encapsulation summary
In five lessons you learned C#'s encapsulation mechanisms. The public, private, protected and internal modifiers control where a member can be seen. Properties provide controlled access with get and set.
Auto-properties shorten the code, init guarantees immutability, required enforces mandatory initialization. Now you will combine all of this in two mini tasks: first a private field and property, then an immutable structure with init.
Exercise Encapsulation in the BankAccount class
Define a BankAccount class. Add a private decimal balance; field and a public decimal Balance { get { return balance; } } read-only property. Add a public void Deposit(decimal amount) method with balance = balance + amount; in the body. Inside Main call Deposit(500) and print Balance.
Show example solution
Add a private balance, a read-only Balance property and a Deposit method to BankAccount. In Main write BankAccount b = new BankAccount(); b.Deposit(500); Console.WriteLine(b.Balance);
Example solution:
using System;
class BankAccount
{
private decimal balance;
public decimal Balance
{
get { return balance; }
}
public void Deposit(decimal amount)
{
balance = balance + amount;
}
}
class Program
{
static void Main()
{
BankAccount b = new BankAccount();
b.Deposit(500);
Console.WriteLine(b.Balance);
}
}
Exercise Use init in the Config class
Define a Config class. Add public required string Environment { get; init; } and public int Timeout { get; init; } = 30; properties. Inside Main create an instance with new Config { Environment = "Production" } and print Environment and Timeout.
Show example solution
Add required Environment and init Timeout properties to Config. In Main write Config c = new Config { Environment = "Production" }; Console.WriteLine(c.Environment); Console.WriteLine(c.Timeout);
Example solution:
using System;
class Config
{
public required string Environment { get; init; }
public int Timeout { get; init; } = 30;
}
class Program
{
static void Main()
{
Config c = new Config { Environment = "Production" };
Console.WriteLine(c.Environment);
Console.WriteLine(c.Timeout);
}
}
Encapsulation complete
Encapsulation is now in your toolkit. Access modifiers control visibility, properties provide controlled access, and auto-properties shorten the code. init adds immutability, required adds mandatory initialization.
These five groups completed C#'s OOP fundamentals: classes, constructors, inheritance, encapsulation and a helper library project. The next sections cover advanced topics such as generics, LINQ and async.
Test yourself
-
Which is accessible only from within the class?
- private
- public
- internal
- protected
Show answer
private — Correct. A private member is accessible only from within the class.
-
Complete the init property
public int X { get; ____; }
Show answer
public int X { get; init; }
Next lesson: Static fields