Table of contents
1.
Introduction
2.
What is the inheritance in C#?
3.
Syntax
4.
Types of Inheritance
4.1.
Single Inheritance
4.1.1.
Example
4.2.
Multilevel inheritance
4.2.1.
Example
4.3.
Hierarchical Inheritance
4.3.1.
Example
4.4.
Multiple inheritance 
4.4.1.
Example 
4.5.
Python
5.
Sealed Keyword
6.
Important Points
7.
Advantages of Inheritance
8.
Disadvantages of Inheritance
9.
Frequently Asked Questions
9.1.
What is inheritance called?
9.2.
What is inheritance and its types?
9.3.
What is multilevel and multiple inheritance in C#?
9.4.
What is the inherited form of C#?
10.
Conclusion
Last Updated: Aug 18, 2024
Easy

Inheritance in C#

Career growth poll
Do you think IIT Guwahati certified course can help you in your career?

Introduction

Inheritance in C# is a fundamental concept of object-oriented programming that allows a class to inherit features and functionalities from another class. This feature supports the reuse of code, which makes it a crucial aspect of efficient software development. In C#, a class that inherits methods and properties from another is known as the derived class or subclass, while the class from which it inherits is referred to as the parent class or superclass. In this article, we will explain inheritance in C# with an example that helps clarify how shared attributes and behaviors can be utilized across different classes. This approach not only simplifies coding but also enhances the maintainability of code. The types of inheritance in C# have single, multilevel, and hierarchical inheritance.

Recommended Topic, Palindrome in C#, singleton design pattern in c#, and Ienumerable vs Iqueryable.

What is the inheritance in C#?

Inheritance in C# is a very important part of OOPS which allows you to create new classes based on existing classes, inheriting their properties and methods. The existing class is called the base or parent class, and the new class is called the derived or child class. Inheritance promotes code reuse and helps organize related classes into a hierarchy. The derived class can add new properties and methods or override the inherited ones. 

Syntax

class derived_class : base_class
{
	// Methods and fields
}


Example

using System;
namespace ConsoleApplication1 {
  
// Base class
class info {
  
  // data members
    public string name;
    public int rollNo;
  
    // public method of base class 
    public void enter(string name, int rollNo)
    {
        this.name = name;
        this.rollNo = rollNo;
        Console.WriteLine("Name : " + name); 
        Console.WriteLine("Roll No : " + rollNo);
    }
}

// Derived class  
// inheriting the info class
class Student : info {
  
    // constructor
    public Student()
    {
        Console.WriteLine("Student Details");
    }
}
  
class Example {
  
    static void Main(string[] args)
    {
        // creating object of derived class
        Student student1 = new Student();
        student1.enter("John Roger", 21);
    }
}
}


Output

Student Details
Name : John Roger
Roll No : 21

Types of Inheritance

Single Inheritance

Single inheritance is defined as the type of inheritance in which a derived class/subclass inherits the methods and fields of only one base class/superclass.

Example

using System;  
  public class oops  
    {  
        public oops() { Console.WriteLine("It is an object-oriented programming language"); }  
  }  
  public class Csharp: oops  
  {  
        public Csharp() { Console.WriteLine("We are coding in Csharp"); }  
  }  
  class SingleInheritance{  
      public static void Main(string[] args)  
        {  
            Csharp d1 = new Csharp();  
        }  
    }  


Output

It is an object-oriented programming language
We are coding in Csharp

Also see, c# interview questions

Multilevel inheritance

Multilevel inheritance is defined as the type of inheritance in which a class is derived from a class which itself is derived from another class. For example, class z is derived from class y, and class y is derived from class x.

Example

using System;  
    
  public class oops  
    {  
        public oops() { Console.WriteLine("It is an object-oriented programming language"); }  
  }  
  public class inheritance  : oops
    {  
        public inheritance() { Console.WriteLine("It supports inheritance"); }  
  }  
  public class Csharp: inheritance  
  {  
        public Csharp() { Console.WriteLine("We are coding in Csharp"); }  
  }  
  class MultilevelInheritance{  
      public static void Main(string[] args)  
        {  
            Csharp d1 = new Csharp();  
        }  
    }  


Output

It is an object-oriented programming language
It supports inheritance
We are coding in Csharp


Hierarchical Inheritance

Hierarchial inheritance is the type of inheritance in which more than one class is derived from a single base class. For example, classes B, C, D are derived from a single base class A.


Example

using System;  
    
  public class X  
    {  
        public int x=10,y=21;
  }  
  public class Y  : X
    {  
        public void add(){
            int sum=this.x + this.y;
            Console.WriteLine("Sum of "+this.x+" and "+this.y +" : "+ sum);
        }  
  }  
  public class Z: X  
  {  
        public void prod(){
        int prod=this.x * this.y;
        Console.WriteLine("Product of "+this.x+" and "+this.y +" : "+ prod);
        }    
  }  
  class HierarchicalInheritance{  
      public static void Main(string[] args)  
        {  
            Y d1 = new Y();  
            d1.add();
            Z d2 = new Z();  
            d2.prod();
        }  
    }  


Output

Sum of 10 and 21 : 31
Product of 10 and 21 : 210

Multiple inheritance 

Multiple inheritance is a feature in some programming languages that allows a class to inherit features and functionalities from more than one parent class. This means a single class can derive properties and methods from multiple base classes. For example, class `C` as `TeachingAssistant` is derived from two base classes `A` as `Teacher` and `B` as `Student`, inheriting features from both.

Example 

  • Python

Python

class Teacher:
def teach(self):
print("Teaching students.")

class Student:
def study(self):
print("Studying the course material.")

class TeachingAssistant(Teacher, Student):
def assist(self):
print("Assisting in the laboratory.")

# Creating an instance of TeachingAssistant
ta = TeachingAssistant()
ta.teach() # Output: Teaching students.
ta.study() # Output: Studying the course material.
ta.assist() # Output: Assisting in the laboratory.
You can also try this code with Online Python Compiler
Run Code

Sealed Keyword

C# is an object-oriented programming language that allows inheritance. But if we don't want a class to be inherited by other classes we use the keyword “sealed” as a prefix during class declaration.

Syntax

sealed class className
{
	// Methods and Fields
}


Example

using System;  
  sealed public class oops  
    {  
        public oops() { Console.WriteLine("It is an object-oriented programming language"); }  
  }  
  public class Csharp: oops  
  {  
        public Csharp() { Console.WriteLine("We are coding in Csharp"); }  
  }  
  class useOfsealed{  
      public static void Main(string[] args)  
        {  
            Csharp d1 = new Csharp();  
        }  
    }


Output

'Csharp': cannot derive from sealed type 'oops'

Important Points

  • A superclass, also known as a base class, can have multiple subclasses or derived classes, but a subclass can have only one superclass because C# doesn’t support multiple inheritance with classes.
     
  • Every class has only one direct superclass, in the absence of any other explicitly superclass, every class is implicitly a subclass of the object class.
     
  • A derived class does not inherit the private members of its base/parent class. If the superclass has properties for accessing its private fields only, then a subclass can inherit the private members of the base class.
     
  • A derived class inherits all the methods and fields of its base class. Derived classes do not inherit constructors, tho the constructor of a base class can be invoked from the derived class.

Advantages of Inheritance

  • By using inheritance, we can reduce redundancy.
  • Using inheritance, we can reuse the code already written and promote reusability.
  • It makes the code more readable by reducing the size of the source code.
  • It makes the code more structured and easy to manage.
  • It supports code extensibility by overriding the base class functionality within the child class.

 

Disadvantages of Inheritance

 

  1. Tight coupling: Inheritance creates a tight coupling between the base class and the derived classes, making the code more fragile and harder to maintain. Changes in the base class can potentially affect all the derived classes.
  2. Increased complexity: As the inheritance hierarchy grows, the complexity of the codebase increases. Deep inheritance hierarchies can make the code harder to understand, debug, and modify.
  3. Lack of flexibility: Inheritance is a static relationship defined at compile-time. It doesn't provide the flexibility to change the behavior of objects at runtime, which can be a limitation in certain scenarios.
  4. Potential for misuse: Inheritance can be misused or overused, leading to inappropriate or excessive hierarchies. It's important to use inheritance judiciously and only when there is a clear "is-a" relationship between classes.
  5. Fragile base class problem: Changes in the base class can inadvertently break the functionality of the derived classes. This is known as the fragile base class problem and can make the system more brittle.
  6. Limited multiple inheritance: C# does not support multiple inheritance of classes, which means a class can only inherit from a single base class. This can be a limitation in situations where multiple inheritance is desired.
  7. Performance overhead: Inheritance introduces a slight performance overhead due to the additional indirection and the need to traverse the inheritance hierarchy during method invocation and property access.
  8. Difficulty in testing: Testing-derived classes can be more challenging because they depend on the behavior of the base class. Changes in the base class may require retesting of all the derived classes.

Know What is Object in OOPs here in detail.

Frequently Asked Questions

What is inheritance called?

Inheritance is referred to as a mechanism in object-oriented programming where one class acquires properties and behaviors from another class.

What is inheritance and its types?

Inheritance allows classes to derive properties and methods from other classes. Types include single, multilevel, hierarchical, multiple, and hybrid.

What is multilevel and multiple inheritance in C#?

Multilevel inheritance in C# allows a class to inherit from a derived class, forming a hierarchy. C# does not support multiple inheritance of classes.

What is the inherited form of C#?

An inherited form in C# is a Windows Forms form that inherits its functionality from another form class, allowing reuse and extension of its visual and functional components.

Conclusion

In this article, we have extensively discussed what inheritance is, how we can implement it, and the different types of inheritance supported in the C# programming language with examples and their implementation in Visual Studio Code.

We hope that this blog has helped you enhance your knowledge regarding inheritance in the C# programming language and if you would like to learn more, check out our articles on understanding the difference between C# and C++, what is Multiple Inheritance in Java, what is hybrid inheritance in Java.

Do upvote our blog to help other ninjas grow. Happy Coding!”

Live masterclass