What is inheritance in C# and how does it work?

What is Inheritance?

Inheritance is a feature of object-oriented programming (OOP) that lets you define a base class that provides specific functionality (data and behavior) and derived classes that either inherit or override that functionality.

Types of Inheritance in C#

– Single Inheritance: A derived class that inherits from only one base class.

– Multi-level Inheritance: A derived class that inherits from a base class and the derived class itself becomes the base class for another derived class.

– Hierarchical Inheritance: A base class that serves as a parent class for two or more derived classes.

– Multiple Inheritance: A derived class that inherits from two or more base classes (only achievable through interfaces).

How Inheritance Works

– A derived class (child) inherits fields and methods from a base class (parent).

– The colon operator (:) is used to show inheritance between two classes.

– The base class can have any number of subclasses, but a subclass can have only one superclass.

– A subclass does not inherit the private members of its parent class.

– A subclass inherits all the members (fields, methods) from its superclass.

– Constructors are not members, so they are not inherited by subclasses, but the constructor of the superclass can be invoked from the subclass.