C# - Inheritance

Inheritance

Creating a new class from existing class is called as inheritance.

Inheritance enables you to create new classes that reuse, extend, and modify the behavior that is defined in other classes. The class whose members are inherited is called the base class, and the class that inherits those members is called the derived class. A derived class can have only one direct base class.

However, inheritance is transitive. If C is derived from B, and B is derived from A, C inherits the members declared in B and A.

Like Java, C# does not support multiple inheritance, meaning that classes cannot inherit from more than one class. You can, however, use interfaces for that purpose in the same way as in Java.

Advantages of Inheritance

  • Reduce code redundancy.
  • Provides code reusability.
  • Reduces source code size and improves code readability.
  • It manages the code easily and divides the class into base class and derived class
  • Supports code extensibility by overriding the base class functionality within child classes.

Disadvantages of Inheritance

  • In Inheritance base class and child classes are tightly coupled. Hence If you change the code of parent class, it will get affects to the all the child classes.
  • In class hierarchy many data members remain unused and the memory allocated to them is not utilized. Hence affect performance of your program if you have not implemented inheritance correctly.

Different Types of Inheritance

Inheritance can be classified to 5 types.

  • Single Inheritance
  • Hierarchical Inheritance
  • Multi Level Inheritance
  • Hybrid Inheritance
  • Multiple Inheritance

Single Inheritance

when a single derived class is created from a single base class then the inheritance is called as single inheritance.

class A
{
}
class B:A
{
}

Hierarchical Inheritance

It is the type of inheritance in which there is one base class and one derived class.

class A
{
}
class B:A
{
}
class C:A
{
}

Multi Level Inheritance

When one class is derived from another derived class then this type of inheritance is called multilevel inheritance.

class A
{
}
class B:A
{
}
class C:B
{
}

Hybrid Inheritance

Any combination of single, hierarchical and multi level inheritances is called as hybrid inheritance.

class A
{
}
class B:A
{
}
class C:A
{
}
class D:B
{
}

Multiple Inheritance

when a derived class is created from more than one base class then that inheritance is called as multiple inheritance. But multiple inheritance is not supported by .net using classes and can be done using interfaces.