Inheritance with base class constructor with parameters

C#InheritanceConstructor

C# Problem Overview


Simple code:

class foo
{
    private int a;
    private int b;

    public foo(int x, int y)
    {
        a = x;
        b = y;
    }
}

class bar : foo
{
    private int c;
    public bar(int a, int b) => c = a * b;
}

Visual Studio complains about the bar constructor: > Error CS7036 There is no argument given that corresponds to the required formal parameter x of foo.foo(int, int).

What?

C# Solutions


Solution 1 - C#

The problem is that the base class foo has no parameterless constructor. So you must call constructor of the base class with parameters from constructor of the derived class:

public bar(int a, int b) : base(a, b)
{
    c = a * b;
}

Solution 2 - C#

I could be wrong, but I believe since you are inheriting from foo, you have to call a base constructor. Since you explicitly defined the foo constructor to require (int, int) now you need to pass that up the chain.

public bar(int a, int b) : base(a, b)
{
     c = a * b;
}

This will initialize foo's variables first and then you can use them in bar. Also, to avoid confusion I would recommend not naming parameters the exact same as the instance variables. Try p_a or something instead, so you won't accidentally be handling the wrong variable.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionzeusalmightyView Question on Stackoverflow
Solution 1 - C#DmitryView Answer on Stackoverflow
Solution 2 - C#guitar80View Answer on Stackoverflow