Control how your objects behave and protect their internal state
Encapsulation is a core principle of OOP. It means bundling data (fields/properties) and behaviour (methods) together, and restricting direct access to internal details. In C#, we use properties and methods to do this.
Letβs break it down with a class-based example and see how it applies in your WinForms apps.
π§± What Is Encapsulation?
Encapsulation means:
- Hiding internal fields from outside interference
- Exposing only whatβs needed through
publicproperties or methods - Protecting object integrity with logic and validation
β
Helps prevent bugs
β
Makes classes easier to understand and use
β
Allows internal changes without breaking outside code
π©βπ« Example: Student Class
public class Student
{
// Private field (hidden from outside)
private int _age;
// Public property (controlled access)
public int Age
{
get { return _age; }
set
{
if (value >= 0)
_age = value;
else
throw new ArgumentException("Age cannot be negative.");
}
}
// Method (encapsulated behaviour)
public string Describe()
{
return $"This student is {_age} years old.";
}
}
β Benefits of Using Properties
Properties are the bridge between fields and the outside world. They allow:
- Validation (e.g. preventing bad data)
- Read-only or write-only access
- Calculated values (e.g.
IsAdult => Age >= 18)
π Read-Only Example
public string FullName { get; } = "Alice Johnson";
β¨ Adding Methods to Represent Actions
Methods represent what the object can do β its behaviour.
public class Cat
{
public string Name { get; set; }
public string Meow()
{
return $"{Name} says: Meow!";
}
public void Eat(string food)
{
Console.WriteLine($"{Name} eats {food}.");
}
}
Use these methods in WinForms to display info or update the UI.
π§ͺ WinForms Example
Cat myCat = new Cat { Name = "Luna" };
MessageBox.Show(myCat.Meow());
Encapsulation means you never directly change internal variables like sound = "meow" β you ask the cat to Meow() instead.
π§ Properties vs Methods
| Use When… | Property | Method |
|---|---|---|
| Represents data/state | β Yes | β Not ideal |
| Represents an action | β No | β Yes |
| May involve logic/validation | β Often | β Often |
| You expect a return value | β (for simple values) | β (for complex logic or action) |
π Summary
| Feature | Purpose | Example |
|---|---|---|
| Private field | Stores internal data | private int _age; |
| Property | Safely access or modify data | public int Age { get; set; } |
| Method | Perform logic or actions | public void Meow() |
β Use properties for access, methods for action
β Best Practices
- β Use private fields for internal storage
- β Use public properties for controlled access
- β
Add validation in
setto enforce rules - β Use methods for meaningful actions (not just setting data)
- β Use PascalCase for property and method names
π§ͺ Quick Challenge
π§© Create a BankAccount class with:
Balance(read-only property)Deposit(decimal amount)methodWithdraw(decimal amount)method that prevents overdraft
Try calling these from a WinForms form and show the balance in a label.
π Want to Go Further?
- Use access modifiers to hide logic (
private,protected,internal) - Explore auto-properties with private setters
- Chain methods and properties for clean APIs (
cat.Eat("fish").Purr()) - Learn about inheritance and override methods later in the course
π¬ Want help designing your class logic for a real app idea (e.g., quiz engine, product form, game logic)?
Send us your concept β Weβll help you structure the class with proper encapsulation or join our OOP C# Course