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
offoo.foo(int, int)
.
What?
This question is related to
c#
inheritance
constructor
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.
Source: Stackoverflow.com