Inheritance in C#
Inheritance in C#
Definition:
Inheritance is an object-oriented feature that allows a class (derived/child class) to acquire
members (fields, methods, etc.) from another class (base/parent class).
1. Single Inheritance
Syntax:
class BaseClass
{
// base members
}
Example:
using System;
class Vehicle
{
public void Start()
{
Console.WriteLine("Vehicle is starting...");
}
}
class Program
{
static void Main()
{
Car myCar = new Car();
myCar.Start();
myCar.Drive();
}
}
Output:
Vehicle is starting...
Car is driving...
2. Multilevel Inheritance
Syntax:
class A { }
class B : A { }
class C : B { }
Example:
using System;
class Person
{
public void Info()
{
Console.WriteLine("I am a person.");
}
}
class Program
{
static void Main()
{
Manager m = new Manager();
m.Info();
m.Work();
m.Manage();
}
}
Output:
I am a person.
Employee is working.
Manager is managing the team.
3. Hierarchical Inheritance
Syntax:
class Base { }
class A : Base { }
class B : Base { }
Example:
using System;
class Animal
{
public void Eat()
{
Console.WriteLine("Animal is eating...");
}
}
class Program
{
static void Main()
{
Dog d = new Dog();
d.Eat();
d.Bark();
Output:
Animal is eating...
Dog is barking...
Animal is eating...
Cat is meowing...
C# does not support multiple class inheritance, but it allows multiple interface
implementation.
Used to achieve multiple behaviors without ambiguity.
Syntax:
interface A { }
interface B { }
class C : A, B { }
Example:
using System;
interface IReader
{
void Read();
}
interface IWriter
{
void Write();
}
class Program
{
static void Main()
{
Author a = new Author();
a.Read();
a.Write();
}
}
Output:
Author is reading...
Author is writing...
5. Hybrid Inheritance (Using Interfaces)
Syntax:
interface A { }
class B { }
class C : B, A { }
Example:
using System;
interface IWorker
{
void DoWork();
}
class Person
{
public void Talk()
{
Console.WriteLine("Person is talking...");
}
}
class Program
{
static void Main()
{
Engineer e = new Engineer();
e.Talk();
e.DoWork();
}
}
Output:
Person is talking...
Engineer is solving problems...
Summary Table
Inheritance Supported in
Description Example Shown
Type C#?
One class inherits from one base
Single ✅ Yes Vehicle → Car
class
Derived class is inherited by Person → Employee →
Multilevel ✅ Yes
another derived class Manager
Multiple classes inherit from one
Hierarchical ✅ Yes Animal → Dog, Cat
base class
One class implements multiple ✅ Yes (via Author : IReader,
Multiple
interfaces interfaces) IWriter
Combination of class and interface Engineer : Person,
Hybrid ✅ Yes
inheritance IWorker