I am new to c# and I'm learning about classes. Here is a piece of code I tried to write. I just wanna know how to subtract "Damage" from "Health", like this : (look at the end)
public void Message()
{
Console.WriteLine(Name + " Has received " + Damage + " Damage which makes his health " + Health - Damage);
}
The problem you have here is with how the compiler compiles this expression, and this has to do with a topic called operator precedence.
Basically it sees this:
string + number - number
Unfortunately it combines the string with the number first and thus you get this:
string - number
Luckily the solution is simple, add parenthesis to get the compiler to evaluate the minus before the plus:
...his health " + (Health - Damage)
^ ^
+-- add these --+
There are also other ways to write your statement so that this operator precedence doesn't come into play. You can use string.Format
:
Console.WriteLine(string.Format("{0} Has received {1} Damage which makes his health {2}", Name, Damage, Health - Damage));
Some methods scattered around the .NET Framework even has support for this way of building a string built in, and Console.WriteLine
is one of them, so you can even shorten the above to this:
Console.WriteLine("{0} Has received {1} Damage which makes his health {2}", Name, Damage, Health - Damage);
Or you can do it with the newer syntax string interpolation:
Console.WriteLine($"{Name} Has received {Damage} Damage which makes his health {Health - Damage}");
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With