VOOZH about

URL: https://www.geeksforgeeks.org/c-sharp/encapsulation-in-c-sharp/

⇱ Encapsulation in C# - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Encapsulation in C#

Last Updated : 17 Sep, 2025

Encapsulation is one of the core principles of object-oriented programming (OOP). It refers to the practice of binding data (fields) and the methods that operate on that data into a single unit, while restricting direct access to some components. This ensures controlled interaction with an object’s internal state.

👁 ecapsulation
Encapsulation

Key Concepts

  • Encapsulation hides the internal representation of an object and exposes only necessary operations.
  • Fields are often kept private while access is provided through public properties or methods.
  • It improves data security, code maintainability and flexibility.
  • Access modifiers (private, public, protected, internal) control visibility of members.

Example:


Output
Balance: 300

Explanation:

  • balance is private and cannot be accessed directly from outside.
  • The class provides controlled methods (Deposit, Withdraw, GetBalance) to interact with the field.

Encapsulation Using Properties

C# provides properties to simplify encapsulation, acting like smart getters and setters.


Output
Student Name: Alex

Explanation:

  • The field name is private.
  • The Name property controls how values are set and retrieved.
  • This improves flexibility compared to public fields.

Advantages

  • Data Protection: Prevents unauthorized access to fields.
  • Controlled Access: Exposes only required operations.
  • Code Flexibility: Internal implementation can change without affecting external code.
  • Maintainability: Reduces coupling between classes.

Disadvantages

  • Using getters and setters adds extra code compared to accessing fields directly.
  • Accessing data through methods may be a bit slower than direct access.
  • Since data is hidden, it can sometimes be difficult to quickly inspect or change values during debugging.
Comment
Article Tags:
Article Tags:

Explore