> For the complete documentation index, see [llms.txt](https://sannlynnhtun.gitbook.io/dotnet-developer/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://sannlynnhtun.gitbook.io/dotnet-developer/c-basic/object-oriented-programming-oop/encapsulation.md).

# 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**

```csharp
class Person {
    // Private field
    private string name;

    // Public property
    public string Name {
        get { return name; } // Getter
        set { 
            if (!string.IsNullOrEmpty(value)) {
                name = value;
            } else {
                throw new ArgumentException("Name cannot be empty.");
            }
        } // Setter
    }

    // Public method
    public void DisplayInfo() {
        Console.WriteLine($"Name: {name}");
    }
}

// Usage
Person person = new Person();
person.Name = "John Doe";  // Using the property
person.DisplayInfo();      // Output: Name: John Doe
```

***

**Example 2: Read-Only and Write-Only Properties**

```csharp
class BankAccount {
    private double balance;

    // Read-only property
    public double Balance {
        get { return balance; }
    }

    // Write-only property
    public double Deposit {
        set {
            if (value > 0) {
                balance += value;
            }
        }
    }
}

// Usage
BankAccount account = new BankAccount();
account.Deposit = 500;  // Adding money to the account
Console.WriteLine(account.Balance);  // Output: 500
```

***

**Example 3: Encapsulation with Constructor**

```csharp
class Product {
    private string name;
    private double price;

    // Constructor for initialization
    public Product(string name, double price) {
        this.name = name;
        this.price = price;
    }

    // Public method
    public void Display() {
        Console.WriteLine($"Product: {name}, Price: {price:C}");
    }
}

// Usage
Product product = new Product("Laptop", 999.99);
product.Display(); // Output: Product: Laptop, Price: $999.99
```

***

#### **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.


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://sannlynnhtun.gitbook.io/dotnet-developer/c-basic/object-oriented-programming-oop/encapsulation.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
