C sharp - Inheritance in C#
Definition:
Inheritance in C# is a fundamental object-oriented programming concept where a child class (derived class) inherits members (fields, methods, properties, etc.) from a parent class (base class).
Key Points:
-
Promotes code reusability by allowing you to build new classes based on existing ones.
-
The derived class automatically gets all non-private members of the base class.
-
Use the
:
symbol to establish inheritance.
Syntax:
class BaseClass {
// base class members
}
class DerivedClass : BaseClass {
// additional or overridden members
}
Benefits of Inheritance:
-
Reusability – no need to rewrite common code.
-
Extensibility – add new features to existing code easily.
-
Polymorphism – enables method overriding for dynamic behavior.
Types of Inheritance Supported in C#:
-
Single Inheritance – one base class and one derived class.
-
Multilevel Inheritance – class inherits from a derived class.
-
Hierarchical Inheritance – multiple classes inherit from one base class.
-
Note: C# does not support multiple inheritance (a class cannot inherit from more than one class), but it can implement multiple interfaces.