Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Concat result of arithmetic operation with string

Tags:

c#

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);
}
like image 992
Dawgx Avatar asked Dec 14 '22 17:12

Dawgx


1 Answers

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}");
like image 168
Lasse V. Karlsen Avatar answered Dec 31 '22 01:12

Lasse V. Karlsen