Home > Mobile >  Resolve Error 'There is no argument given that corresponds to the required formal parameter
Resolve Error 'There is no argument given that corresponds to the required formal parameter

Time:01-17

I am new to C# and .Net, I have following code where I'm getting error while compiling in C# visual Studio 2022. Can someone kindly explain what am I doing wrong and how can I rectify it?

class Vehicle
{
    public string company;                  //class field
    public void ignition()                  //class method
    {                 
        Console.WriteLine("Vroom Vroom");
    }

    public Vehicle (string companyName)     //class parameterized constructor
    {
        company = companyName;
    }
}

class Car : Vehicle
{
    public string model;                //class field

    public Car (string modelName)       //class parameterized constructor //this is where the error occurs
    {
        model = modelName;
    }
}

CodePudding user response:

To fix, the derived class should call base

public Car (string modelName) : base(modelName)

But in your case, design is not good enough. Potential fix is

class Car : Vehicle
{
    public string model;                //class field

    public Car (string modelName, string company) : base(company)       //class parameterized constructor //this is where the error occurs
    {
        model = modelName;
    }
}

The concept is that if you have explicit constructor in the base class, you must use that. Unless you explicitly define the parameter-less constructor. So, you need to pass your company through derived class constructor to the base class.

  •  Tags:  
  • c#
  • Related