CHASH Tutorial



C# INHERITANCE


C# Inheritance

Inheritance in C# allows a class (called derived class) to acquire properties and methods from another class (called base class). It promotes code reusability and makes applications easier to maintain.

๐Ÿ“˜ Basic Syntax:
class DerivedClass : BaseClass

Example: Simple Inheritance

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

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

class Program
{
    static void Main()
    {
        Dog myDog = new Dog();
        myDog.Eat();   // Inherited from Animal
        myDog.Bark();  // Defined in Dog
    }
}
  
โœ… Output:
Eating...
Barking...

Inheritance Types in C#

  • Single Inheritance โ€“ One base class, one derived class
  • Multilevel Inheritance โ€“ Inheritance in a chain (A โ†’ B โ†’ C)
  • Hierarchical Inheritance โ€“ One base class, multiple derived classes
  • Multiple Inheritance โ€“ Not supported directly, but can be achieved via interfaces

Multilevel Inheritance Example

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

class Mammal : Animal
{
    public void Walk() => Console.WriteLine("Walking...");
}

class Human : Mammal
{
    public void Speak() => Console.WriteLine("Speaking...");
}

class Program
{
    static void Main()
    {
        Human person = new Human();
        person.Eat();    // From Animal
        person.Walk();   // From Mammal
        person.Speak();  // From Human
    }
}
  
๐Ÿงพ Output:
Eating...
Walking...
Speaking...

Base Keyword

Use base to access members of the base class from the derived class.

class Vehicle
{
    public Vehicle()
    {
        Console.WriteLine("Vehicle constructor");
    }
}

class Car : Vehicle
{
    public Car() : base()
    {
        Console.WriteLine("Car constructor");
    }
}
  
โ›“๏ธ When an object of Car is created, the base class constructor Vehicle() runs first.

Key Takeaways

  • Inheritance promotes reusability and cleaner code
  • Use : BaseClass to inherit
  • Use base keyword to call base class members
  • C# does not support multiple class inheritance directly

๐ŸŒŸ Enjoyed Learning with Us?

Help others discover Technorank Learning by sharing your honest experience.
Your support inspires us to keep building!

Leave a Google Review