0
0
CsharpConceptBeginner · 3 min read

What is Inheritance in C#: Explanation and Example

In C#, inheritance is a way to create a new class that takes properties and methods from an existing class. It helps reuse code and build relationships between classes by allowing one class to extend another.
⚙️

How It Works

Inheritance in C# works like a family tree. Imagine you have a basic blueprint for a car. You can create a new blueprint for a sports car that uses everything from the basic car but adds special features like a turbo engine. The sports car 'inherits' the common parts from the basic car.

In programming, this means a new class (called the child or derived class) gets all the properties and behaviors (methods) of an existing class (called the parent or base class). The child class can also add new features or change existing ones. This saves time because you don’t have to write the same code again.

Inheritance helps organize code in a clear way, showing how different things are related, just like family members share traits but are still unique.

💻

Example

This example shows a base class Animal and a derived class Dog that inherits from Animal. The Dog class can use the Speak method from Animal and also has its own method Bark.

csharp
using System;

class Animal
{
    public void Speak()
    {
        Console.WriteLine("The animal makes a sound.");
    }
}

class Dog : Animal
{
    public void Bark()
    {
        Console.WriteLine("The dog barks.");
    }
}

class Program
{
    static void Main()
    {
        Dog myDog = new Dog();
        myDog.Speak();  // Inherited method
        myDog.Bark();   // Own method
    }
}
Output
The animal makes a sound. The dog barks.
🎯

When to Use

Use inheritance when you have different objects that share common features but also have their own unique parts. For example, in a game, you might have a general Character class and then specific classes like Wizard and Warrior that inherit from it but add special skills.

It helps keep your code clean and easy to maintain because shared code stays in one place. It also makes it easier to add new types later without rewriting everything.

Key Points

  • Inheritance lets a class reuse code from another class.
  • The base class is the original, and the derived class extends it.
  • Derived classes can add or change features.
  • It models real-world relationships and keeps code organized.

Key Takeaways

Inheritance allows a class to reuse and extend code from another class.
It helps organize code by showing relationships between classes.
Derived classes can add new features or override existing ones.
Use inheritance to avoid repeating code and to model real-world hierarchies.