Inheritance in C#
Inheritance is one of the important concepts of Object-Oriented Programming (OOP) in C#. It allows one class to acquire the members and behavior of another class.
In simple words, inheritance allows us to create a new class using an existing class. The new class can reuse existing functionality and can also add its own functionality.
What is Inheritance?
Inheritance is a mechanism in which a class derives its members from another class. The existing class is called the base class, and the new class is called the derived class.
| Term | Meaning |
|---|---|
| Base Class | The class whose members are inherited. |
| Derived Class | The class that inherits from the base class. |
| Inheritance | The relationship through which the derived class gets accessible members from the base class. |
Inheritance Syntax in C#
In C#, inheritance is specified using a colon : between the derived class and the base class.
// Parent class members
}
class Child : Parent
{
// Child class members
}
Here, Child is the derived class and Parent is the base class.
Why Do We Need Inheritance?
- Avoids duplicate code.
- Allows code reusability.
- Helps organize related classes.
- Allows derived classes to extend existing functionality.
- Supports polymorphism.
- Makes large applications easier to maintain.
Simple Inheritance Program
Let's understand inheritance using a simple Person and Student example.
using System;
class Person
{
public string Name { get; set; }
public void DisplayName()
{
Console.WriteLine( $"Name: {Name}");
}
}
class Student : Person
{
public string Course { get; set; }
public void DisplayCourse()
{
Console.WriteLine( $"Course: {Course}");
}
}
class Program
{
static void Main()
{
Student student = new Student();
student.Name = "Rahul";
student.Course = "C# Full Stack";
student.DisplayName();
student.DisplayCourse();
}
};
Program Output
Course: C# Full Stack
Program Explanation
| Code | Explanation |
|---|---|
| class Person | Creates the base class named Person. |
| Name | Property used to store the person's name. |
| DisplayName() | Method defined in the Person class. |
| class Student : Person | Student inherits from Person. |
| Course | Property specific to the Student class. |
| student.Name | Student can access the inherited Name property. |
| student.DisplayName() | Student can call the inherited method. |
| student.DisplayCourse() | Calls the method defined inside Student. |
Base Class and Derived Class
The class from which another class inherits is called the base class. The class that inherits is called the derived class.
// Base class
}
class Car : Vehicle
{
// Derived class
}
Here, Vehicle is the base class and Car is the derived class.
Example: Vehicle 👨🏫❤️
A vehicle can have common properties and behaviors such as brand, speed, and starting. A car can reuse those common features and add car-specific functionality.
using System;
class Vehicle
{
public string Brand { get; set; }
public void Start()
{
Console.WriteLine( "Vehicle started.");
}
}
class Car : Vehicle
{
public void Drive()
{
Console.WriteLine( "Car is driving.");
}
}
class Program
{
static void Main()
{
Car car = new Car();
car.Brand = "Toyota";
Console.WriteLine( $"Brand: {car.Brand}");
car.Start();
car.Drive();
}
}
Output
Vehicle started.
Car is driving.
The Car object can access the Brand property and Start() method inherited from Vehicle. It can also use its own Drive() method.
What Can Be Inherited?
A derived class can access inherited members according to their accessibility. Public and protected members can be available to the derived class, while private members of the base class are not directly accessible in the derived class.
| Member | Directly Accessible in Derived Class? |
|---|---|
| public | Yes |
| protected | Yes |
| private | No |
Protected Members
The protected access modifier allows a member to be accessed inside its containing class and inside derived classes.
{
protected string Name;
}
class Student : Person
{
public void SetName()
{
Name = "Rahul";
}
}
The Student class can access the protected Name member because Student derives from Person.
Multilevel Inheritance
In multilevel inheritance, a class derives from another derived class, creating a chain of inheritance.
{
public void ShowGrandParent()
{
Console.WriteLine( "GrandParent");
}
}
class Parent : GrandParent
{
public void ShowParent()
{
Console.WriteLine( "Parent");
}
}
class Child : Parent
{
public void ShowChild()
{
Console.WriteLine( "Child");
}
}
A Child object can access the accessible members of both Parent and GrandParent through the inheritance chain.
Hierarchical Inheritance
In hierarchical inheritance, multiple derived classes inherit from the same base class.
{
public void Start()
{
Console.WriteLine( "Vehicle started.");
}
}
class Car : Vehicle
{
}
class Bike : Vehicle
{
}
Both Car and Bike inherit from Vehicle.
The base Keyword
The base keyword is used to access members of the base class from a derived class. It can also be used to call a base class constructor.
{
protected string Name = "Rahul";
}
class Student : Person
{
public void Display()
{
Console.WriteLine( base.Name);
}
}
Constructor with Inheritance
When a derived class object is created, the base class portion of the object is initialized before the derived class constructor body runs.
{
public Person()
{
Console.WriteLine( "Person constructor");
}
}
class Student : Person
{
public Student()
{
Console.WriteLine( "Student constructor");
}
}
Student student = new Student();
Student constructor
Calling Base Constructor using base()
The base() constructor initializer can be used to pass values from a derived class constructor to a base class constructor.
{
public string Name { get; set; }
public Person( string name)
{
Name = name;
}
}
class Student : Person
{
public Student( string name) : base(name)
{
}
}
Inheritance and Method Overriding
Inheritance is closely related to method overriding. A derived class can provide its own implementation of a virtual method defined in the base class.
The virtual keyword allows a base class method to be overridden, and the override keyword is used in the derived class.
{
public virtual void Sound()
{
Console.WriteLine( "Animal makes a sound.");
}
}
class Dog : Animal
{
public override void Sound()
{
Console.WriteLine( "Dog barks.");
}
}
Method overriding is an important part of polymorphism, which we will study in more detail in the next OOP topics.
Types of Inheritance in C#
| Type | Meaning |
|---|---|
| Single | One derived class inherits from one base class. |
| Multilevel | Inheritance occurs in multiple levels. |
| Hierarchical | Multiple derived classes inherit from the same base class. |
| Multiple | C# classes do not support multiple class inheritance directly. Multiple interfaces can be implemented instead. |
Multiple Inheritance using Interfaces
C# does not allow a class to inherit directly from multiple classes. However, a class can implement multiple interfaces.
{
}
interface ISavable
{
}
class Document : IPrintable, ISavable
{
}
This allows a class to implement contracts from multiple interfaces without inheriting implementation from multiple base classes.
Advantages of Inheritance
- Code Reusability: Existing functionality can be reused.
- Less Duplicate Code: Common functionality can remain in the base class.
- Extensibility: Derived classes can add new behavior.
- Maintainability: Common changes can often be made in the base class.
- Polymorphism: Inheritance enables important polymorphic designs.
Common Beginner Mistakes
- Confusing the base class and derived class.
- Assuming private members can be directly accessed in the derived class.
- Using inheritance only for code reuse when the classes do not have a meaningful "is-a" relationship.
- Forgetting to use virtual and override when overriding a base class method.
- Thinking that C# supports multiple class inheritance.
- Creating unnecessarily deep inheritance hierarchies.
The "Is-A" Relationship
Inheritance generally represents an "is-a" relationship.
| Derived Class | Base Class | Relationship |
|---|---|---|
| Car | Vehicle | Car is a Vehicle |
| Dog | Animal | Dog is an Animal |
| Student | Person | Student is a Person |
| Manager | Employee | Manager is an Employee |
CIIT Practical Point
In professional C# development, inheritance is used when classes have a meaningful relationship and common behavior can be placed in a base class.
In ASP.NET Core and enterprise applications, developers may work with base classes, derived classes, abstract classes, and framework types.
A good developer should not use inheritance only for code reuse. The relationship between the classes should make logical sense.
CIIT Interview Points
- What is inheritance in C#?
- What is a base class?
- What is a derived class?
- How do you implement inheritance in C#?
- What is the purpose of the : symbol in class declaration?
- What is the base keyword?
- What is the difference between public, protected, and private members in inheritance?
- What is multilevel inheritance?
- Does C# support multiple class inheritance?
- What is method overriding?
- What is the difference between virtual and override?
Summary
- Inheritance allows one class to derive from another class.
- The existing class is called the base class.
- The new class is called the derived class.
- Inheritance improves code reuse and extensibility.
- C# uses : to specify class inheritance.
- public and protected members can be available to derived classes according to their accessibility.
- Private base-class members are not directly accessible in the derived class.
- C# supports single, multilevel, and hierarchical class inheritance.
- C# does not support multiple inheritance between classes, but multiple interfaces can be implemented.
- Inheritance is an important foundation for polymorphism and other OOP concepts.
Practice Questions
- Create a Person base class with Name and Age.
- Create a Student class that inherits from Person.
- Add Course and RollNumber to Student.
- Create an object of Student and display all details.
- Create a Vehicle base class and derive Car from it.
- Create a multilevel inheritance example using GrandParent, Parent, and Child.
- Create two classes derived from the same base class to demonstrate hierarchical inheritance.
- Create a virtual method in a base class and override it in a derived class.
- Explain the difference between base and this keywords.