Open In App

C# | Inheritance

Last Updated : 06 Apr, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

Introduction:

Inheritance is a fundamental concept in object-oriented programming that allows us to define a new class based on an existing class. The new class inherits the properties and methods of the existing class and can also add new properties and methods of its own. Inheritance promotes code reuse, simplifies code maintenance, and improves code organization.

In C#, there are several types of inheritance:

In C#, there are 4 types of inheritance:

  1. Single inheritance: A derived class that inherits from only one base class.
  2. 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.
  3. Hierarchical inheritance: A base class that serves as a parent class for two or more derived classes.
  4. Multiple inheritance: A derived class that inherits from two or more base classes.

Here’s an example code that demonstrates each type of inheritance:

C#




using System;
 
// single inheritance
class Animal {
    public void Eat() {
        Console.WriteLine("Animal is eating.");
    }
}
 
class Dog : Animal {
    public void Bark() {
        Console.WriteLine("Dog is barking.");
    }
}
 
// multi-level inheritance
class Mammal : Animal {
    public void Run() {
        Console.WriteLine("Mammal is running.");
    }
}
 
class Horse : Mammal {
    public void Gallop() {
        Console.WriteLine("Horse is galloping.");
    }
}
 
// hierarchical inheritance
class Bird : Animal {
    public void Fly() {
        Console.WriteLine("Bird is flying.");
    }
}
 
class Eagle : Bird {
    public void Hunt() {
        Console.WriteLine("Eagle is hunting.");
    }
}
 
class Penguin : Bird {
    public void Swim() {
        Console.WriteLine("Penguin is swimming.");
    }
}
 
// multiple inheritance
interface I1 {
    void Method1();
}
 
interface I2 {
    void Method2();
}
 
class MyClass : I1, I2 {
    public void Method1() {
        Console.WriteLine("Method1 is called.");
    }
 
    public void Method2() {
        Console.WriteLine("Method2 is called.");
    }
}
 
// main program
class Program {
    static void Main(string[] args) {
        // single inheritance
        Dog dog = new Dog();
        dog.Eat();
        dog.Bark();
 
        // multi-level inheritance
        Horse horse = new Horse();
        horse.Eat();
        horse.Run();
        horse.Gallop();
 
        // hierarchical inheritance
        Eagle eagle = new Eagle();
        Penguin penguin = new Penguin();
        eagle.Fly();
        eagle.Hunt();
        penguin.Fly();
        penguin.Swim();
 
        // multiple inheritance
        MyClass myClass = new MyClass();
        myClass.Method1();
        myClass.Method2();
 
        Console.ReadLine();
    }
}


Output

Animal is eating.
Dog is barking.
Animal is eating.
Mammal is running.
Horse is galloping.
Bird is flying.
Eagle is hunting.
Bird is flying.
Penguin is swimming.
Method1 is called.
Method2 is called.

Advantages of Inheritance:

  1. Code Reusability: Inheritance allows us to reuse existing code by inheriting properties and methods from an existing class.
  2. Code Maintenance: Inheritance makes code maintenance easier by allowing us to modify the base class and have the changes automatically reflected in the derived classes.
  3. Code Organization: Inheritance improves code organization by grouping related classes together in a hierarchical structure.

Disadvantages of Inheritance:

  1. Tight Coupling: Inheritance creates a tight coupling between the base class and the derived class, which can make the code more difficult to maintain.
  2. Complexity: Inheritance can increase the complexity of the code by introducing additional levels of abstraction.
  3. Fragility: Inheritance can make the code more fragile by creating dependencies between the base class and the derived class.

Reference book:

Here are some recommended books for learning about inheritance in C#:

  1. “C# 9.0 in a Nutshell” by Joseph Albahari and Ben Albahari: This book provides a comprehensive guide to C# 9.0, including inheritance, interfaces, and other object-oriented programming concepts.
  2. “Head First C#” by Jennifer Greene and Andrew Stellman: This book is a beginner-friendly introduction to C#, including inheritance and other object-oriented programming concepts.
  3. “Professional C# 7 and .NET Core 2.0” by Christian Nagel: This book is a comprehensive guide to C# 7 and .NET Core 2.0, including inheritance, polymorphism, and other object-oriented programming concepts.

These books are great resources for both beginners and experienced developers who want to learn more about inheritance in C#.

Inheritance is an important pillar of OOP(Object Oriented Programming). It is the mechanism in C# by which one class is allowed to inherit the features(fields and methods) of another class. Important terminology:

  • Super Class: The class whose features are inherited is known as super class(or a base class or a parent class).
  • Sub Class: The class that inherits the other class is known as subclass(or a derived class, extended class, or child class). The subclass can add its own fields and methods in addition to the superclass fields and methods.
  • Reusability: Inheritance supports the concept of “reusability”, i.e. when we want to create a new class and there is already a class that includes some of the code that we want, we can derive our new class from the existing class. By doing this, we are reusing the fields and methods of the existing class.

How to use inheritance

The symbol used for inheritance is :. Syntax:

class derived-class : base-class  
{  
   // methods and fields  
   .
   .
}  

Example: In below example of inheritance, class GFG is a base class, class GeeksforGeeks is a derived class which extends GFG class and class Sudo is a driver class to run program. 

Csharp




// C# program to illustrate the
// concept of inheritance
using System;
namespace ConsoleApplication1 {
 
// Base class
class GFG {
  
   // data members
    public string name;
    public string subject;
 
    // public method of base class
    public void readers(string name, string subject)
    {
        this.name = name;
        this.subject = subject;
        Console.WriteLine("Myself: " + name);
        Console.WriteLine("My Favorite Subject is: " + subject);
    }
}
 
// inheriting the GFG class using :
class GeeksforGeeks : GFG {
  
    // constructor of derived class
    public GeeksforGeeks()
    {
        Console.WriteLine("GeeksforGeeks");
    }
}
  
// Driver class
class Sudo {
 
    // Main Method
    static void Main(string[] args)
    {
  
        // creating object of derived class
        GeeksforGeeks g = new GeeksforGeeks();
 
        // calling the method of base class
        // using the derived class object
        g.readers("Kirti", "C#");
    }
}
}


Output:

GeeksforGeeks
Myself: Kirti
My Favorite Subject is: C#

Types of Inheritance in C#

Below are the different types of inheritance which is supported by C# in different combinations.

  1. Single Inheritance: In single inheritance, subclasses inherit the features of one superclass. In image below, the class A serves as a base class for the derived class B.
  2. Multilevel Inheritance: In Multilevel Inheritance, a derived class will be inheriting a base class and as well as the derived class also act as the base class to other class. In below image, class A serves as a base class for the derived class B, which in turn serves as a base class for the derived class C.
  3. Hierarchical Inheritance: In Hierarchical Inheritance, one class serves as a superclass (base class) for more than one subclass. In below image, class A serves as a base class for the derived class B, C, and D.
  4. Multiple Inheritance(Through Interfaces):In Multiple inheritance, one class can have more than one superclass and inherit features from all parent classes. Please note that C# does not support multiple inheritance with classes. In C#, we can achieve multiple inheritance only through Interfaces. In the image below, Class C is derived from interface A and B.
  5. Hybrid Inheritance(Through Interfaces): It is a mix of two or more of the above types of inheritance. Since C# doesn’t support multiple inheritance with classes, the hybrid inheritance is also not possible with classes. In C#, we can achieve hybrid inheritance only through Interfaces.

Important facts about inheritance in C#

  • Default Superclass: Except Object class, which has no superclass, every class has one and only one direct superclass(single inheritance). In the absence of any other explicit superclass, every class is implicitly a subclass of Object class.
  • Superclass can only be one: A superclass can have any number of subclasses. But a subclass can have only one superclass. This is because C# does not support multiple inheritance with classes. Although with interfaces, multiple inheritance is supported by C#.
  • Inheriting Constructors: 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.
  • Private member inheritance: A subclass does not inherit the private members of its parent class. However, if the superclass has properties(get and set methods) for accessing its private fields, then a subclass can inherit.


Previous Article
Next Article

Similar Reads

C# | Multilevel Inheritance
Introduction: In object-oriented programming, inheritance is the ability to create new classes that are derived from existing classes, known as base or parent classes. Inheritance allows the derived classes to inherit properties and methods of the base classes and to add new features or functionalities to the derived classes. Inheritance is a power
7 min read
C# | Inheritance in Constructors
Introduction: Inheritance in constructors is a feature in C# that allows a derived class to inherit the constructor of its base class. This means that the derived class can use the constructor of the base class to initialize its own fields and properties. This feature saves a lot of code duplication and makes it easier to create derived classes tha
8 min read
C# | Inheritance in interfaces
C# allows the user to inherit one interface into another interface. When a class implements the inherited interface then it must provide the implementation of all the members that are defined within the interface inheritance chain.Important Points: If a class implements an interface, then it is necessary to implement all the method that defined by
3 min read
C# | Multiple inheritance using interfaces
Introduction:Multiple inheritance refers to the ability of a class to inherit from multiple base classes. C# does not support multiple inheritance of classes, but it does supportmultiple inheritance using interfaces. An interface is a collection of abstract methods that a class can implement to provide specific behavior. A class canimplement multip
7 min read
C# Program For Hierarchical Inheritance
Inheritance is a basic aspect of object-oriented programming. A superclass, also known as a base class, is a class whose members are inherited, whereas a subclass, also known as a derived class, is a class that inherits from a superclass. They are also known as the parent and child classes, respectively. In the same way that a child inherits the tr
4 min read
C# Program to Demonstrate Abstract Class with Multiple-level Inheritance
Abstract Class is the way to achieve abstraction. It is a special class that never be instantiated directly. This class should contain at least one abstract method in it and mark by abstract keyword in the class definition. The main purpose of this class is to give a blueprint for derived classes and set some rules what the derived classes must imp
3 min read
C# Program to Demonstrate Interface Implementation with Multi-level Inheritance
Multilevel Inheritance is the process of extending parent classes to child classes in a level. In this type of inheritance, a child class will inherit a parent class, and as well as the child class also act as the parent class to other class which is created. For example, three classes called P, Q, and R, where class R is derived from class Q and c
3 min read
C# Program to Demonstrate the Inheritance of Abstract Classes
Abstraction is the process to hide the internal details and show only the functionality. The abstract keyword is used before the class or method to declare the class or method as abstract. And inheritance is the object-oriented programming methodology by which one class is allowed to inherit the features(fields and methods) of another class. In C#,
2 min read
C# Program to Implement Multiple-Inheritance using Abstract Class and Interface
Given multiple inheritance, now our task is to implement multiple inheritance with the help of abstract class and interface. So, before implementation first of all we learn the basic definition of multiple-inheritance, abstract class, and interface. Multiple inheritance: Multiple inheritance is a type of inheritance that is followed in object-orien
4 min read