C# Encapsulation

What is Encapsulation?

Encapsulation is the practice of hiding data inside a class and controlling how it is accessed.

Instead of allowing direct access to variables, you use properties to safely read and modify data.

Loading...
Output:

Why Use Encapsulation?

Encapsulation protects your data from incorrect or unwanted changes.

  • Prevents invalid values
  • Improves security
  • Makes code easier to maintain
  • Allows controlled updates

Private Fields

Fields should usually be marked as private so they cannot be accessed directly from outside the class.

This forces users of the class to go through controlled methods or properties.

Loading...
Output:

Using Properties for Access

Properties provide a safe way to access private fields.

They allow you to control both reading (get) and writing (set) of data.

Loading...
Output:

Adding Validation

One of the biggest advantages of encapsulation is adding validation when setting values.

This prevents invalid data from being stored.

Loading...
Output:

Encapsulation in Action

Here is a full example showing encapsulation working in a program.

Loading...
Output:

Encapsulation vs Public Fields

Using public fields is not recommended because it allows unrestricted access.

Encapsulation provides control and prevents errors.

Loading...
Output:

Why Encapsulation Matters in C#

Encapsulation is a core concept in object-oriented programming and is widely used in real-world applications.

  • Used in APIs and data models
  • Essential for ASP.NET applications
  • Improves code reliability

Practice

Create a BankAccount class with a private balance. Use a property to control deposits and prevent negative values.

Loading...
Output:

Need Help?