Reputation: 57
I'm trying to inherit from a base class but I'm getting an error that I can't figure out. This is the base class:
class Item
{
protected string name;
public Item(string name)
{
this.name = name;
}
}
And this is the inherited class:
class ItemToBuy : Item
{
private int lowPrice;
private int highPrice;
private int maxQuantity;
public ItemToBuy(int lowPrice, int highPrice, int maxQuantity) : base(name)
{
this.lowPrice = lowPrice;
this.highPrice = highPrice;
this.maxQuantity = maxQuantity;
}
}
The issue is this line:
public ItemToBuy(int lowPrice, int highPrice, int maxQuantity) : base(name)
where 'name' is underlined with the error message "An object reference is required for the non-static field, method or property 'Item.name'. If I replace it with a string literal the error message isn't there. What am I doing wrong with inheriting the constructor?
Upvotes: 0
Views: 1026
Reputation: 6335
your ItemToBuy class does not have any knowledge of "name". The way you build the constructor, "name" needs to be a defined string.
Let's say that your constructor looks like this:
class ItemToBuy : Item
{
private int lowPrice;
private int highPrice;
private int maxQuantity;
public ItemToBuy(int lowPrice, int highPrice, int maxQuantity, string name) : base(name)
{
this.lowPrice = lowPrice;
this.highPrice = highPrice;
this.maxQuantity = maxQuantity;
}
}
this will work because the name parameter is defined.
So, you either do it like that or pass a hardcoded value like you did to make it work.
Upvotes: 4
Reputation: 654
you need to receive the name in the constructor of ItemToBuy:
public ItemToBuy(int lowPrice, int highPrice, int maxQuantity,string name) : base(name)
Upvotes: 0
Reputation: 23898
public ItemToBuy(int lowPrice, int highPrice, int maxQuantity) : base(name)
{
this.lowPrice = lowPrice;
this.highPrice = highPrice;
this.maxQuantity = maxQuantity;
}
should be changed to:
public ItemToBuy(int lowPrice, int highPrice, int maxQuantity, string name) : base(name)
{
this.lowPrice = lowPrice;
this.highPrice = highPrice;
this.maxQuantity = maxQuantity;
}
You need to specify the name
parameter in the constructor, as per my code above.
Upvotes: 0
Reputation: 16575
You need to have the name in the ctor of the ItemToBuy class too
public ItemToBuy(string name ,int lowPrice, int highPrice, int maxQuantity) : base(name)
Upvotes: 2