Encapsulation
Encapsulation is a fundamental concept in object-oriented programming (OOP) that refers to the bundling of data (attributes) and methods (functions) that operate on that data within a single unit, typically a class. Encapsulation provides a way to restrict direct access to an object's internal state and allows manipulation of that state only through the object's public methods. This ensures that the object's internal data remains consistent and secure, and it promotes modularity, maintainability, and reusability in code.
One common way to implement encapsulation is by using access modifiers (such as public, private, and protected) to control the visibility of class members. By making attributes private and exposing them through public methods (getters and setters, also known as accessor and mutator methods), you can control how the data is accessed and modified.
Another common way to implement encapsulation in C# is by using properties with backing fields. Properties allow you to expose an object's data while providing a mechanism to control access and modification. Backing fields are private fields that store the actual data, while the public properties provide controlled access to those fields.
Here's an example demonstrating encapsulation with properties and backing fields in C#:
In this example, the Employee class has two private backing fields, _name and _age, and their corresponding public properties Name and Age. Notice that the code places restrictions on setting the field values. By using these properties, you can control how the _name and _age fields are accessed and modified, ensuring that only valid values are assigned to them. This protects the object's internal state and enforces data integrity.
Here is a good video on YouTube about C# Getters and Setters that explains some use cases for encapsulation: