C# Inheritance

C# Inheritance

Inheritance in C# is an OOP concept that allows a class (derived/child class) to reuse properties and methods of another class (base/parent class).
It promotes code reusability and hierarchical relationships.


🔹 Syntax


 

  • : symbol is used to indicate inheritance.


🔹 Simple Example



 


🔹 Types of Inheritance in C#

  1. Single Inheritance – One child inherits one parent

  2. Multilevel Inheritance – Chain of inheritance



 

  1. Hierarchical Inheritance – Multiple children inherit one parent



 

C# does not support multiple class inheritance (Child cannot inherit from multiple classes)
Use interfaces for multiple inheritance.


🔹 Access Modifiers in Inheritance

ModifierInheritance Access
publicAccessible everywhere
protectedAccessible in derived class
privateNot inherited
internalAccessible in same assembly

🔹 Using base Keyword

Access base class members:


 


🔹 Method Overriding

  • Use virtual in base class

  • Use override in derived class


 


🔹 Sealed Classes

  • Prevents a class from being inherited


 


🔹 Common Mistakes

❌ Trying multiple class inheritance
❌ Accessing private base members
❌ Forgetting virtual for overriding


🔹 Summary

✔ Derived classes inherit base class members
✔ Promotes code reusability
base keyword accesses parent members
✔ Use virtual and override for polymorphism
✔ C# allows single, multilevel, hierarchical inheritance

You may also like...