Encapsulation

C# Encapsulation

Encapsulation is one of the core principles of object-oriented programming (OOP) in C#. It is the process of bundling data (fields) and methods (functions) that operate on the data into a single unit, usually a class. Encapsulation restricts direct access to certain components of an object, enhancing security, modularity, and code maintainability.


Key Features of Encapsulation

  1. Data Hiding

    • Fields or properties are kept private, limiting direct access.

    • Access is provided through public methods or properties (getters and setters).

  2. Access Modifiers

    • Control the visibility of class members.

    • Examples: private, protected, public, internal.

  3. Properties

    • Provide a controlled way to access or modify private fields.

  4. Improved Modularity

    • Classes act as self-contained units, making the code easier to maintain.


Benefits of Encapsulation

  1. Data Protection

    • Prevents unauthorized access and modification.

  2. Ease of Maintenance

    • Internal implementation changes do not affect external code.

  3. Improved Readability

    • Clearly defined interfaces for accessing data.


Encapsulation in Action

Example 1: Using Private Fields and Properties


Example 2: Read-Only and Write-Only Properties


Example 3: Encapsulation with Constructor


Access Modifiers and Encapsulation

Modifier

Description

Example Usage

private

Accessible only within the class.

Internal data fields.

public

Accessible from anywhere.

Methods, interfaces, properties.

protected

Accessible within the class and derived classes.

For inheritance scenarios.

internal

Accessible within the same assembly.

Shared classes within a project.

protected internal

Accessible within the same assembly or derived classes.

Mixed accessibility requirements.


Key Points

  • Encapsulation uses access modifiers to control visibility and access.

  • Properties are a structured way to enforce rules when accessing fields.

  • Private fields provide internal protection while exposing controlled access via public interfaces.


Summary

  • Encapsulation ensures data integrity by restricting direct access to class members.

  • Controlled access is provided via properties and methods.

  • Benefits include better data protection, modular code, and easier maintenance.

  • Use encapsulation to safeguard your codebase, ensuring robustness and clarity in object design.

Encapsulation is a vital component of object-oriented programming, promoting cleaner, safer, and more maintainable code.