Inheritance :

May 11, 2011
  • Inheritance is a way to form new classes (instances of which are called objects) using classes that have already been defined.
  • Inheritance is employed to help reuse existing code with little or no modification.
  • The new classes, known as Sub-class or derived class, inherit attributes and behavior of the pre-existing classes, which are referred to as Super-class or Base class.

C# supports two types of Inheritance mechanisms

1) Implementation Inheritance
2) Interface Inheritance

Implementation Inheritance:

When a class (type) is derived from another class (type) such that it inherits all the members of the base type it is Implementation Inheritance

Interface Inheritance:

When a type (class or a struct) inherits only the signatures of the functions from another type it is Interface Inheritance.

Benefits of using Inheritance

  • Once a behavior (method) or property is defined in a super class (base class),that behavior or property is automatically inherited by all subclasses (derived class).
  • Code reusability increased through inheritance
  • Inheritance provide a clear model structure which is easy to understand without much complexity
  • Using inheritance, classes become grouped together in a hierarchical tree structure
  • Code are easy to manage and divided into parent and child classes
public class ParentClass { public ParentClass() { Console.WriteLine("Parent Constructor."); } public void print() { Console.WriteLine("Parent Class."); } } public class ChildClass : ParentClass { public ChildClass() { Console.WriteLine("Child Constructor."); } public static void Main() { ChildClass child = new ChildClass(); child.print(); } }

Parent Constructor.
Child Constructor.
Parent Class.