Sobes.tech
Junior

What is encapsulation?

sobes.tech AI

Answer from AI

Encapsulation is a mechanism that allows hiding the internal state of an object and protecting it from external interference. It combines data (fields) and methods that work with these data into a single unit — a class.

In C#, encapsulation is achieved using access modifiers (public, private, protected, internal, protected internal, private protected) and properties.

Example using properties:

public class Person
{
    private int _age; // Private field

    public int Age // Public property provides controlled access to the _age field
    {
        get { return _age; }
        set
        {
            if (value >= 0) // Data validation
            {
                _age = value;
            }
            else
            {
                // You can throw an exception or perform another action
                Console.WriteLine("Age cannot be negative.");
            }
        }
    }

    public string Name { get; set; } // Auto-implemented property

    public void DisplayInfo()
    {
        Console.WriteLine($"Name: {Name}, Age: {Age}");
    }
}

Advantages of encapsulation:

  • Hiding implementation details: The internal details of the object are hidden from external code.
  • Access control: Data access is performed through methods or properties, allowing validation and business logic.
  • Flexibility: Changes in the internal implementation of the class do not affect external code that uses its interface.
  • Improved maintainability: The code becomes more structured and understandable.