Open In App

C# | Inheritance in Constructors

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

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 that are closely related to their base classes.

Advantages:

  1. Code reuse: Inheritance in constructors enables the derived class to reuse the constructor of the base class, saving a lot of code duplication and making the code more concise.
  2. Saves time: Inheritance in constructors saves time as developers don’t have to write the same code again and again.
  3. Easy to maintain: Inheritance in constructors makes it easier to maintain the code as changes made in the base class constructor are automatically inherited by the derived class constructors.

Disadvantages:

  1. Tight coupling: Inheritance in constructors can lead to tight coupling between the base class and the derived class, making it difficult to modify the base class without affecting the derived class.
  2. Complexity: Inheritance in constructors can make the code more complex and harder to understand, especially if there are multiple levels of inheritance.

Reference books:

  1. “C# 8.0 and .NET Core 3.0 – Modern Cross-Platform Development: Build applications with C#, .NET Core, Entity Framework Core, ASP.NET Core, and ML.NET using Visual Studio Code, 4th Edition” by Mark J. Price
  2. “C# in Depth, 4th Edition” by Jon Skeet
  3. “Head First C#: A Learner’s Guide to Real-World Programming with C#, XAML, and .NET” by Andrew Stellman and Jennifer Greene

In C#, when we use inheritance, we can also inherit the constructors of the base class. This can be useful in situations where we want to reuse the code of the base class constructor in the derived class constructor.

To inherit a constructor from the base class, we use the base keyword followed by the parameter list of the base class constructor. The base keyword refers to the constructor of the base class.

Here is an example:

C#




using System;
 
class Vehicle
{
    public int speed;
 
    public Vehicle(int speed)
    {
        this.speed = speed;
    }
}
 
class Car : Vehicle
{
    public string model;
 
    public Car(int speed, string model) : base(speed)
    {
        this.model = model;
    }
}
 
class Program
{
    static void Main(string[] args)
    {
        Car car = new Car(60, "Toyota");
 
        Console.WriteLine("Car Model: {0}, Speed: {1}", car.model, car.speed);
    }
}


Output

Car Model: Toyota, Speed: 60

In the example above, we have a Vehicle class with a constructor that takes an int parameter for the speed. We then have a Car class that inherits from the Vehicle class and has an additional property for the model. The Car class constructor uses the base keyword to inherit the Vehicle class constructor, passing in the speed parameter. The model parameter is then assigned to the model property of the Car class.

When we create an instance of the Car class and pass in values for the speed and model parameters, the Car class constructor calls the Vehicle class constructor using the base keyword, passing in the speed parameter. The model parameter is then assigned to the model property of the Car class. Finally, we print out the model and speed properties of the car object.

In C#, both the base class and the derived class can have their own constructor. The constructor of a base class used to instantiate the objects of the base class and the constructor of the derived class used to instantiate the object of the derived class. In inheritance, the derived class inherits all the members(fields, methods) of the base class, but derived class cannot inherit the constructor of the base class because constructors are not the members of the class. Instead of inheriting constructors by the derived class, it is only allowed to invoke the constructor of base class. In C#, when we are working with the constructor in inheritance there are two different cases arise as follows: Case 1: In this case, only derived class contains a constructor. So the objects of the derived class are instantiated by that constructor and the objects of the base class are instantiated automatically by the default constructor. Example: 

CSharp




// C# program to illustrate the
// concept of inheritance in the
// constructor when the derived
// class contains a constructor
using System;
 
// Class Tank to give the
// dimension of the tank
class Tank {
 
    double t_radius;
    double t_height;
 
    // Properties for Radius and Height
    public double Radius
    {
        get {
               return t_radius;
            }
 
        set {
               t_radius = value < 0 ? -value : value;
            }
    }
 
    public double Height
    {
        get {
               return t_height;
            }
 
        set {
              t_height = value < 0 ? -value : value;
            }
    }
 
    // Display the dimension of tanks
    public void DisplayDimension()
    {
        Console.WriteLine("The radius of tank is :" + Radius
                 + " and the height of tank is :" + Height);
    }
}
 
// A derived class AreaOfTank
// inheriting Tank Class
class AreaOfTank : Tank {
 
    string Color;
 
    // Constructor
    public AreaOfTank(string c, double r, double h)
    {
 
        // from base class
        Radius = r;
        Height = h;
 
        // from derived class
        Color = c;
    }
 
    // Return area of tank
    public double Area()
    {
        return 2 * 3.14 * Radius * Height;
    }
 
    // Display the color of tank
    public void DisplayColor()
    {
        Console.WriteLine("The Color of tank is "
                                        + Color);
    }
}
 
// Driver Class
class GFG {
 
    // Main Method
    static void Main()
    {
 
        // Create and initialize the
        // object of AreaOfTank
        AreaOfTank t1 = new AreaOfTank("Green", 6.0, 12.0);
        t1.DisplayColor();
        t1.DisplayDimension();
        Console.WriteLine("Area is " + t1.Area());
    }
}


Explanation: In the above example Tank is the base class and AreaOfTank is the derived class. Tank class provides the dimensions of the tank and AreaOfTank provides the color and the area of the tank. And Tank class does not contain any constructor so the default constructor is used to instantiate the object of class and AreaOfTank class contains AreaOfTank() constructor which instantiate the object of class. Case 2: In this case, both the base class and derived class has their own constructors, so the process is complicated because the constructors of both classes must be executed. To overcome this situation C# provide a keyword known as a base keyword. With the help of base keyword, the derived class can call the constructor which is defined in its base class. Note: Any form of the constructor defined in the base class can be called by the base keyword, but only that constructor executes that matches the arguments. Syntax:

derived-constructor(parameter-list) : base(argument-list)
{
   // body of constructor 
}

Here, argument-list contains arguments that are required by the constructor of the base class. Example: 

CSharp




// C# program to illustrate the concept of
// inheritance in constructors when both
// the base class and derived class
// their own constructors
using System;
 
// Class Tank to give the
// dimension of the tank
class Tank {
 
    double t_radius;
    double t_height;
 
    // Constructor for Tank
    public Tank(double r, double h)
    {
        Radius = r;
        Height = h;
    }
 
    // Properties for Radius
    // and Height
    public double Radius
    {
        get {
               return t_radius;
            }
 
        set {
               t_radius = value < 0 ? -value : value;
            }
    }
 
    public double Height
    {
        get {
               return t_height;
             }
 
        set {
                t_height = value < 0 ? -value : value;
            }
    }
 
    // Display the dimension of tanks
    public void DisplayDimension()
    {
        Console.WriteLine("The radius of tank is :" + Radius
                 + " and the height of tank is :" + Height);
    }
}
 
// AreaOfTank is derived class
// which is inheriting the Tank class
class AreaOfTank : Tank {
 
    string Color;
 
    // Call the Constructor of the
    // base class, i.e Tank
    // Using base keyword
    public AreaOfTank(string c, double r,
                   double h) : base(r, h)
    {
        Color = c;
    }
 
    // Return area of tank
    public double Area()
    {
        return 2 * 3.14 * Radius * Height;
    }
 
    // Display the color of tank
    public void DisplayColor()
    {
        Console.WriteLine("The Color of tank is " + Color);
    }
}
 
// Driver Class
class GFG {
 
    // Main Method
    static void Main()
    {
        // Create and initialize the
        // object of AreaOfTank
        AreaOfTank t1 = new AreaOfTank("Brown", 4.0, 8.0);
        t1.DisplayColor();
        t1.DisplayDimension();
        Console.WriteLine("Area is " + t1.Area());
    }
}


Explanation: In the above example, Tank is the base class and AreaOfTank is the derived class. The Tank class describes the dimension of the tank and AreaOfTank describe the color and the area of the tank. Both the base class and the derived class have their own constructor. But we declare the constructor of AreaOfTank with a base keyword as shown here:

public AreaOfTank(string c, double r, double h) : base (r, h)
{
   Color = c; 
}

Here AreaOfTank() call base class constructor with the parameter r and h. That means Tank() constructor is called and it will initialize the value of Radius and Height in AreaOfTank(). So there is no need for AreaOfTank class to initialize these values. If AreaOfTank required an extra field, then the field should be unique from the called fields like Color. By using the base keyword, it becomes easier to initialize the objects of the base class without any conflict and it also provides an authority to call the constructor of a base class from the derived class and also save the time of re-writing the codes.



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads