0
0
C Sharp (C#)programming~5 mins

Why inheritance is needed in C Sharp (C#)

Choose your learning style9 modes available
Introduction

Inheritance helps us reuse code and organize related things easily. It lets one class get features from another, so we don't repeat ourselves.

When you have many things that share common features, like different types of animals.
When you want to add new features to an existing class without changing it.
When you want to group similar classes under one main class for easier management.
When you want to write code that works with different but related objects in the same way.
When you want to improve or extend the behavior of a class without rewriting it.
Syntax
C Sharp (C#)
class BaseClass {
    // common features
}

class DerivedClass : BaseClass {
    // extra features
}

The DerivedClass inherits all features from BaseClass.

Use : to show inheritance in C#.

Examples
Dog inherits from Animal, so Dog can Eat and Bark.
C Sharp (C#)
class Animal {
    public void Eat() {
        Console.WriteLine("Eating food");
    }
}

class Dog : Animal {
    public void Bark() {
        Console.WriteLine("Barking");
    }
}
Car inherits Start from Vehicle and adds Honk.
C Sharp (C#)
class Vehicle {
    public void Start() {
        Console.WriteLine("Starting vehicle");
    }
}

class Car : Vehicle {
    public void Honk() {
        Console.WriteLine("Honking horn");
    }
}
Sample Program

This program shows how Dog inherits Eat() from Animal and also has its own Bark() method.

C Sharp (C#)
using System;

class Animal {
    public void Eat() {
        Console.WriteLine("Eating food");
    }
}

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

class Program {
    static void Main() {
        Dog myDog = new Dog();
        myDog.Eat();  // inherited method
        myDog.Bark(); // own method
    }
}
OutputSuccess
Important Notes

Inheritance helps avoid repeating the same code in multiple classes.

Derived classes can use and add to the features of base classes.

Use inheritance carefully to keep code simple and clear.

Summary

Inheritance lets one class get features from another to reuse code.

It helps organize related classes and add new features easily.

Use inheritance to write cleaner and more maintainable code.