This is my Program.cs:
int currentHp = 100;
Potion potion = new Potion(10);
Console.WriteLine(potion.ToString(currentHp));
This is my class called Potion.cs
private int hpHeal;
public Potion(int hpHeal)
{
HpHeal = hpHeal;
}
public int HpHeal
{
get { return hpHeal; }
set
{
hpHeal = value;
}
}
public override string ToString(int currentHp)
{
if (currentHp hpHeal > 100)
{
string result = "";
result = $"You healed for {100 - currentHp} hp.\n";
currentHp = 100;
result = $"Current health: {currentHp} hp.";
return result;
}
else
{
string result = "";
currentHp = hpHeal;
result = $"You healed for{hpHeal} hp.\n";
result = $"Current health: {currentHp} hp.";
return result;
}
}
The line public override string ToString(int currentHp)
is underlined with an error
'Potion.ToString(int)': no suitable method found to override
and I don't know why... I'm currently learning how Classes work so don't judje me too hard.
CodePudding user response:
ToString
is a "predefined" method that cannot take any arguments. In your case, simply rename your method (e.g., to Stringify
) and remove the override
keyword from its definition.
CodePudding user response:
You’re trying to override a method which doesn’t exists at all in the base class.
You need to rename your ToString
method to some meaningful name as per your business logic like GetCustomString
One suggestion, you should also rename int hpHeal;
because you have same parameter in the constructor, it’s confusing. Better name it something like _hpHeal
.
And your can also reduce the number of string assignments here, few are unnecessarily affecting performance as string are immutable and it creates a new string when you assign it again.