Encapsulation, Inheritance, and Polymorphism

The core of OOP in C#

Posted by Rodrigo Castro on November 15, 2024

C# is built on object-oriented programming (OOP), which is powered by three main ideas.

🔒 Encapsulation

Keep data safe inside a class.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
class BankAccount
{
    private decimal balance; // Only accessible inside BankAccount

    public void Deposit(decimal amount)
    {
        balance += amount;
    }

    public decimal GetBalance()
    {
        return balance;
    }
}

🧬 Inheritance

Let one class build on another.

1
2
3
4
5
6
7
8
9
10
11
12
class Animal
{
    public void Eat() => Console.WriteLine("Eating...");
}

class Dog : Animal
{
    public void Bark() => Console.WriteLine("Woof!");
}
Dog d = new Dog();
d.Eat();  // From Animal
d.Bark(); // From Dog

🔁 Polymorphism

One interface, many forms.

1
2
3
4
5
6
7
8
9
10
class Animal
{
    public virtual void Speak() => Console.WriteLine("Animal sound");
}
class Cat : Animal
{
    public override void Speak() => Console.WriteLine("Meow");
}
Animal a = new Cat();
a.Speak(); // Meow

📝 Why it matters

  • Encapsulation: Protects data.
  • Inheritance: Reuses code.
  • Polymorphism: Makes code flexible.

Next: Access modifiers in C#!