0Pricing
C# Academy · Lesson

Encapsulation and Access Modifiers

Learn how encapsulation protects data and how access modifiers control visibility.

Encapsulation and Access Modifiers is a free C# Academy lesson on CoddyKit — lesson 5 of 7. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the C# Academy learning path, one of 7 lessons in the course, and your progress syncs across the web and the CoddyKit app.

1

Encapsulation and Access Modifiers

Welcome to the next lesson! In this lesson, you’ll learn about encapsulation, an essential concept in OOP, and how access modifiers control the visibility of class members in C#. Let’s get started!

Encapsulation and Access Modifiers — illustration 1

2

What is Encapsulation?

Encapsulation is the process of bundling data (fields) and behavior (methods) into a single unit (class) while restricting direct access to some components. This is done to protect the integrity of the data and enforce rules for accessing it.

Key Point: Encapsulation allows you to hide implementation details and expose only the functionality that is necessary.

3

Why is Encapsulation Important?

Encapsulation provides several benefits:

  • Data Protection: Prevent unauthorized or invalid access to class fields.
  • Code Maintainability: Changes to internal implementation do not affect external code.
  • Improved Modularity: Keeps code organized and easy to understand.

Example: A class with private fields and public methods to manage those fields demonstrates encapsulation.

4

Understanding Access Modifiers

Access modifiers in C# define the scope of accessibility for class members:

  • public: Accessible from anywhere.
  • private: Accessible only within the same class.
  • protected: Accessible within the same class and derived classes.
  • internal: Accessible within the same assembly.
  • protected internal: Accessible within the same assembly or derived classes.

Key Point: Use access modifiers to enforce encapsulation.

5

Example: Encapsulation with Private Fields

Here’s an example of encapsulation using private fields and public methods:

Key Point: Use private fields to restrict direct access and public methods to expose controlled functionality.

using System;

class BankAccount {
    private decimal balance; // Private field

    public void Deposit(decimal amount) {
        if (amount > 0) {
            balance += amount;
        } else {
            Console.WriteLine("Deposit amount must be positive.");
        }
    }

    public decimal GetBalance() {
        return balance; // Access balance through a method
    }
}

class Program {
    static void Main() {
        BankAccount account = new BankAccount();
        account.Deposit(100.50m); // Deposit money
        Console.WriteLine("Balance: $" + account.GetBalance()); // Get balance
    }
}

6

Encapsulation with Properties

Properties provide a cleaner way to encapsulate fields while allowing validation logic. Example:

Tip: Use properties instead of raw getters and setters for better readability.

using System;

class BankAccount {
    private decimal balance; // Private field

    public decimal Balance { // Property with validation
        get { return balance; }
        set {
            if (value >= 0) {
                balance = value;
            } else {
                Console.WriteLine("Balance cannot be negative.");
            }
        }
    }
}

class Program {
    static void Main() {
        BankAccount account = new BankAccount();
        account.Balance = 200; // Set balance
        Console.WriteLine("Balance: $" + account.Balance); // Get balance
    }
}

7

Practice Challenge

Create a class called Student with private fields Name and Age. Use properties to encapsulate these fields and ensure age is always positive. Example:

using System;

class Student {
    private string name;
    private int age;

    public string Name {
        get { return name; }
        set { name = value; }
    }

    public int Age {
        get { return age; }
        set {
            if (value > 0) {
                age = value;
            } else {
                Console.WriteLine("Age must be positive.");
            }
        }
    }
}

class Program {
    static void Main() {
        Student student = new Student();
        student.Name = "Alice";
        student.Age = 20;

        Console.WriteLine("Name: " + student.Name);
        Console.WriteLine("Age: " + student.Age);
    }
}

8

9

Best Practices for Encapsulation

Here are some best practices:

  • Always use private fields for sensitive data.
  • Use properties or methods to validate and control access to fields.
  • Combine encapsulation with access modifiers to protect your code.

Tip: Encapsulation helps you build secure and maintainable applications.

10

Great Job!

Congratulations! You’ve learned how to use encapsulation and access modifiers to protect and organize your data. In the next lesson, we’ll explore inheritance and learn how to reuse code efficiently. Let’s keep coding!

Encapsulation and Access Modifiers — illustration 10

Frequently asked questions

Is the “Encapsulation and Access Modifiers” lesson free?

Yes — the full text of “Encapsulation and Access Modifiers” is free to read here on the web, and the C# Academy course includes 7 lessons in total. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the C# Academy course, upgrade to CoddyKit PRO.

What will I learn in “Encapsulation and Access Modifiers”?

Learn how encapsulation protects data and how access modifiers control visibility. You practise C# Academy with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.

Do I need any experience to start C# Academy?

No prior experience is required. C# Academy on CoddyKit is structured for beginners through advanced learners; this is — lesson 5 of 7, so you can start here or from the beginning and move at your own pace.

How long does the “Encapsulation and Access Modifiers” lesson take?

Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.

Can I write and run code in this C# Academy lesson?

Yes. Every C# Academy lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.

All lessons in this course

  1. What is Object-Oriented Programming?
  2. Defining Classes and Objects
  3. Understanding Properties and Methods
  4. Constructors in C#
  5. Encapsulation and Access Modifiers
  6. Inheritance: Reusing Code
  7. Polymorphism and Method Overriding
← Back to C# Academy