Revisiting Encapsulation in C#
Revisiting Encapsulation
Welcome back! After diving deep into classes in our last session, we're now shifting our focus to another essential concept in Object-Oriented Programming (OOP): encapsulation.
Encapsulation bundles data (fields) and methods (functions) that operate on the data, restricting direct access to some of an object's components. This prevents accidental modification of data by keeping the data attributes private and providing public methods to access and modify them. By ensuring that the internal state of the object can only be changed in controlled ways, you can maintain consistency and prevent errors.
Create Private Fields
Let's start by defining a simple Person class with private fields. To apply encapsulation, we need to make the fields private by using the private keyword:
Now, name and age are private fields, meaning they cannot be accessed directly from outside the Person class. Instead, we will provide public accessors to interact with these fields.
Properties for Accessors
In C#, we commonly use properties to provide controlled access to private fields. Properties are a cleaner and more idiomatic way to implement getters and setters in C#:
In this example, the Name and Age properties use getter and setter methods to provide controlled access to the private name and age fields.
Auto-Implemented Properties
In addition to defining custom getters and setters, C# provides a more concise syntax called auto-implemented properties. This allows you to define properties without explicitly declaring private fields:
With auto-implemented properties, the compiler automatically creates a private, anonymous backing field that can only be accessed through the property's get and set accessors. This can make the code more concise and readable while still providing controlled access to the fields.
