Encapsulation in C#
Hide the engine under the hood. Expose only the steering wheel and pedals.
60-Second Version: Encapsulation = data hiding. Make fields
private. Control access with public properties. Protect from bad data.1. Problem: Public Fields = No Control
public class Car
{
public int Speed; // Anyone can set Speed = -500. Bad!
}
Car c = new Car();
c.Speed = -999; // Car going backwards at 999? Nonsense
2. Solution: Private Field + Public Property
public class Car
{
private int speed; // Hidden. Only Car can touch this
public int Speed // Public door with security check
{
get { return speed; }
set
{
if(value >= 0) speed = value; // Block negative speed
}
}
}
Car c = new Car();
c.Speed = -999; // Ignored. speed stays 0
c.Speed = 100; // Works
Beginner Trap:
public int Speed { get; set; } with no logic is same as public field. Add validation in set or use private field.
Quick Check ๐ง
Next: Constructors & Destructors - Build and cleanup objects properly.
No comments yet. Be the first to share your thoughts!