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#
Single Inheritance – One child inherits one parent
Multilevel Inheritance – Chain of inheritance
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
| Modifier | Inheritance Access |
|---|---|
| public | Accessible everywhere |
| protected | Accessible in derived class |
| private | Not inherited |
| internal | Accessible in same assembly |
🔹 Using base Keyword
Access base class members:
🔹 Method Overriding
Use
virtualin base classUse
overridein 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
