-1

I have a base class that takes one argument in the constructor Then I create a child class and I also use a constructor with on argument.

The idea is that the constructor of DeviceA overrides the constructor of GenericDevice

However the system complains

Error   CS7036  There is no argument given that corresponds to the required formal parameter 'address' of 'GenericDevice.GenericDevice(string)' 

I'm not sure why this error happens, since DeviceA doesn't need the constructor of GenericDevice, it has its own

class GenericDevice {
    GenericDevice(string address){
    
    }
    void Connect() {
    }
}

class DeviceA : GenericDevice
{
    DeviceA(string address) {

    }
    void Foo() {
    }
}
Sembei Norimaki
  • 5,656
  • 2
  • 31
  • 62

2 Answers2

0

Fix your code like this:

class GenericDevice
{
    protected GenericDevice(string address)
    {
    }

    void Connect()
    {
    }
}

class DeviceA : GenericDevice
{
    DeviceA(string address) : base(address)
    {
    }

    void Foo()
    {
    }
}

In a derived class, if a base-class constructor is not called explicitly by using the base keyword, the parameterless constructor, if there is one, is called implicitly. https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/classes-and-structs/using-constructors

So you also can change your code like this:

class GenericDevice
{
    protected GenericDevice()
    {
    }

    GenericDevice(string address)
    {
    }

    void Connect()
    {
    }
}

class DeviceA : GenericDevice
{
    DeviceA(string address)
    {
    }

    void Foo()
    {
    }
}
Infosunny
  • 448
  • 4
  • 17
  • If the constructors is `private` (which is the case if no modifier of the type `protected`, `public`, etc. is present) it can only be called by explicit `: base( ... )` or implicit `: base()` in case the inheriting class is nested inside the base class. Example: `class B { B() { } class C : B { } }` – Jeppe Stig Nielsen Oct 28 '21 at 12:45
0
class GenericDevice
{
    public GenericDevice()
    {

    }
    public GenericDevice(string address)
    {

    }
    void Connect()
    {
    }
}

class DeviceA : GenericDevice
{
    public DeviceA(string address) : base(address)
    {
        // calls the GenericDevice(string address) Constructor
    }


    public DeviceA(string address, int number) : base()
    {
        // calls the GenericDevice() Constructor
    }

    void Foo()
    {
    }
}