Skip to content

Encapsulation

Sann Lynn Htun edited this page Nov 19, 2024 · 1 revision

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

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

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

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.

C# Basics Wiki

Core Concepts

Object-Oriented Programming (OOP)

Advanced Topics

Miscellaneous

Tools and Resources

Clone this wiki locally