What is Inheritance?
It's a mechanism of consuming the members of one class in another class by establishing a parent/child relationship between the classes, which provides reusability. I you want to learn about Inheritance in C#, you can go through a detailed article on C#Corner here- Inheritance with examples in C#.
Syntax
Example
As per the above example, We can also call.
- X = > Parent, Base, Super Class
- Y => Child, Derived, Sub Class
Key Points
- In Inheritance, the child class can consume members of its parent class if it is the Owner of those members.
- In the Inheritance child class can not consume private members of its parent class.
- Parent classes constructor must be accessible to the child class. Otherwise, Inheritance is not possible.
- In Inheritance, the child class can access parent class members, but parent classes can never access any child class members.
- In C#, we don't support multiple Inheritance through classes. But we can achieve this using Interface
- The default access modifier of class members in C# is private.
- The default access modifier of a C# class is internal.
Types Of Inheritance in C#
In C#, there are four types of Inheritance. Read more about types of Inheritance in C# here on C#Corner- Types of Inheritance In C#.
Single Inheritance in C#
C# class can only inherit from one base class is called single Inheritance.
Example
MultiLevel Inheritance in C#
C# class can inherit from a derived class derived from another parent class.
Example
Hierarchical Inheritance in C#
C# class can have multiple child classes inherited from the same parent class.
Multiple Inheritance in C#
C# does not support multiple Inheritance through classes; a class cannot inherit from more than one base class at the same time.
Note. C# does support multiple inheritances through interfaces.
Example