Introduction
In this blog, I will explain inheritance in C#. Inheritance is the most important pillar of OOPS (Object-Oriented Programming). The class whose members are inherited is called the 'base class', 'super class', or 'parent class'. The class that inherits those members is called the 'derived class', 'child class' or 'sub class'.
Inheritance is the base class for the derived class. It inherits all variables, methods, properties, and indexers defined by the base class and adds its own unique elements. Inheritance supports reusability by allowing us to extend an existing class. Inheritance also increases the functionality of a derived class and promotes the reusability of the code and base class. Inheritance is used if we want to create a class and reuse methods or properties from existing classes, then implement the inheritance.
The following types are used in inheritance: Single inheritance, Multi-level inheritance, multiple inheritances, Multipath inheritance, Hierarchical Inheritance, and Hybrid Inheritance.
Syntax
- class Car {
- }
- class Bike: Car {
- }
Example
- public class A {
- public void testA(int carSpeed, int Bikespeed) {
-
- int carspeed = carSpeed;
- int bikespeed = Bikespeed;
- Console.WriteLine("Carspeed=" + carSpeed);
- Console.WriteLine("Bikespeed=" + bikespeed);
- }
-
- }
- public class B: A {
- public void testB() {
- Console.WriteLine("Vechile Speed test");
- }
- }
- public class test {
- public void Main() {
- B speed = new B();
- speed.testA(80, 20);
- }
- }