Skip to main content
C# Fundamentals for Beginners to Advanced
CHAPTER 17 Beginner

Encapsulation and Abstraction in C#

Updated: May 17, 2026
5 min read

# CHAPTER 17

Encapsulation and Abstraction

1. Introduction

We have covered two pillars of OOP: Inheritance and Polymorphism. Now we focus on the remaining two: Encapsulation and Abstraction. These concepts are about security and simplicity. Encapsulation protects your data from being corrupted, while Abstraction hides complex logic so other developers don't have to worry about how things work behind the scenes.

2. Learning Objectives

By the end of this chapter, you will be able to:
  • Implement Encapsulation using private fields and public Properties.
  • Understand the concept of Data Hiding.
  • Implement Abstraction using abstract classes and methods.

3. Encapsulation: Data Hiding

Imagine a BankAccount class. If the balance variable is public, anyone can write account.balance = -1000000;. This is disastrous.

Encapsulation dictates that internal data should be private (hidden). The only way to interact with that data is through controlled, public methods or Properties that contain validation logic.

csharp
123456789101112131415161718192021222324252627
using System;

class BankAccount
{
    // 1. HIDDEN DATA (Private Field)
    private decimal _balance = 0;

    // 2. CONTROLLED ACCESS (Public Property)
    public decimal Balance
    {
        get { return _balance; } // Read-only access
    }

    // 3. CONTROLLED MODIFICATION (Public Method with Validation)
    public void Deposit(decimal amount)
    {
        if (amount > 0)
        {
            _balance += amount;
            Console.WriteLine($"Deposited: ${amount}");
        }
        else
        {
            Console.WriteLine("Invalid deposit amount.");
        }
    }
}

4. Abstraction: Hiding Complexity

Abstraction focuses on *what* an object does, hiding *how* it does it. When you hit the brakes in your car, you don't need to know the hydraulic fluid pressure mathematics; you just need the car to stop.

In C#, we achieve this using the abstract keyword.

5. Abstract Classes and Methods

An Abstract Class is a restricted class that cannot be instantiated (you cannot use new on it). It exists solely to act as a base class for other classes to inherit from.

An Abstract Method is a method that has no body. It *forces* the child class to provide the implementation.

csharp
1234567891011121314151617181920212223242526272829303132333435363738394041
// Abstract Class (Cannot instantiate 'new Shape()')
abstract class Shape
{
    // Abstract Method (No body, forces child to implement)
    public abstract double CalculateArea();

    // Regular Method (Inherited normally)
    public void Display()
    {
        Console.WriteLine("Displaying shape...");
    }
}

// Child class MUST implement CalculateArea()
class Circle : Shape
{
    private double _radius;

    public Circle(double radius)
    {
        _radius = radius;
    }

    // Using the 'override' keyword is mandatory
    public override double CalculateArea()
    {
        return 3.14159 * _radius * _radius;
    }
}

class Program
{
    static void Main()
    {
        // Shape s = new Shape(); // ERROR! Cannot instantiate abstract class.
        
        Shape myCircle = new Circle(5);
        myCircle.Display();
        Console.WriteLine($"Area: {myCircle.CalculateArea()}");
    }
}

6. Why use Abstraction?

Abstraction allows you to define a strict contract. If you are the Lead Architect on a team, you can create an abstract DatabaseConnection class with an abstract Connect() method. You then assign your junior developers to write SqlServerConnection and MongoDbConnection. The compiler will *guarantee* that both of their classes have a Connect() method, ensuring standard architecture across the project.

7. Common Mistakes

  • Writing logic in an abstract method: Abstract methods cannot have curly braces {}. They just end in a semicolon. Example: public abstract void DoWork();
  • Forgetting override: When a derived class implements an abstract method, it must use the override keyword.

8. Best Practices

  • Default to making all class fields private and exposing them only via Properties.
  • Use Abstract classes when you have some shared logic (like the Display method above) but want to force child classes to implement specific missing pieces.

9. Exercises

  1. 1. Create a User class with a private _password field. Create a public method SetPassword(string pwd) that only updates the password if it is longer than 6 characters.
  1. 2. Create an abstract class Vehicle with an abstract method HonkHorn(). Create a Truck class that implements it.

10. MCQs with Answers

Question 1

What is the primary purpose of Encapsulation?

Question 2

Which access modifier is used to hide fields for Encapsulation?

Question 3

How do external classes safely interact with encapsulated private fields?

Question 4

What does Abstraction focus on?

Q5. Can you instantiate an Abstract class (e.g., new AbstractClass())? a) Yes b) No Answer: b) No
Question 6

What MUST a child class do if it inherits an Abstract method?

Q7. Can an Abstract class contain regular, fully implemented methods? a) Yes b) No, it can only contain abstract methods Answer: a) Yes (This is a key difference between Abstract Classes and Interfaces).
Question 8

Which keyword is required when implementing an abstract method in the child class?

Question 9

If a class has at least one Abstract method, the class itself MUST be marked as:

Q10. Is an Auto-Implemented Property (public int Age { get; set; }) an example of Encapsulation? a) Yes, the compiler generates a hidden private backing field behind the scenes b) No, because it is public Answer: a) Yes

11. Interview Questions

  • Q: Explain the difference between Abstraction and Encapsulation.
  • Q: Can an abstract class have a constructor in C#? (Answer: Yes, it can have a constructor to initialize its own fields, which is called when the derived class is instantiated).

12. Summary

Encapsulation acts as a protective shield for your object's internal data, using private fields and public Properties. Abstraction acts as a simplification tool, hiding complex logic behind clean contracts using abstract classes and methods, ensuring consistency across large applications.

13. Next Chapter Recommendation

In Chapter 18: Interfaces and Abstract Classes, we will learn about Interfaces, the ultimate tool for Abstraction that bypasses C#'s rule against multiple inheritance.

Finish this Chapter

Save your progress on your learning path and prepare for coding interview challenges.

Discussion

Join the discussion

Log in or create a free account to participate.

Sort: ·