Dawgx
Dawgx

Reputation: 65

Concat result of arithmetic operation with string

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);
}

Upvotes: 4

Views: 275

Answers (3)

Romeo Sierra
Romeo Sierra

Reputation: 1756

While @Lasse gives the necessary modification as an answer, I would recommend using Formatted Strings instead.

string.Format("{0} Has received {1} Damage which makes his health {2}", Name, Damage, (Health - Damage));

Upvotes: 1

Vladyslav Hrehul
Vladyslav Hrehul

Reputation: 73

You can`t use classes as variable. You should create variables in your classes and operate on them(Create an instance of a class and on instance you will have all your variables and methods). Then you could easily do what you want.

Upvotes: -1

Lasse V. Karlsen
Lasse V. Karlsen

Reputation: 391536

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}");

Upvotes: 12

Related Questions