Encapsulation
Encapsulation is the practice of bundling an object’s data (fields or attributes) with the methods (or functions) that operate on that data. It also involves restricting direct access to some of an object’s components, typically by using access modifiers (public, private, protected, internal). This safeguards an object’s internal state from unintended external modification.
In C#
A common way to achieve encapsulation in C# is to declare fields as private, and provide public properties (getters and setters) to control access to and modification of the object’s state.
public class Person{ private string name; // Private variable, inaccessible outside the class public string Name // Public property to access the private variable { get { return name; } set { name = value; } // Can add validation logic here }}Where it matters
Encapsulation is fundamental for creating robust and maintainable code. By hiding the internal state and controlling access through public interfaces (properties and methods), a class can change its internal implementation without affecting other parts of the system that depend on it. This promotes modularity and reduces the ripple effect of changes.
For instance, the Person class could change how name is stored internally, for example by splitting it into first and last names, without altering the public Name property, as long as the getter and setter logic is updated accordingly.
This interplay with abstractionAbstractionExpose what an object does, and hide how it does it.Opens in a new tab is key. Encapsulation manages the internal state, while abstraction defines the usable interface. Together they achieve significant decoupling in software systems.
Sources
- C# Object Oriented (How It Works For Developers), IronPDF · accessed May 16, 2025