user2884461
user2884461

Reputation: 109

Adding Numbers in C#

I currently have this, but it keeps resulting in the number say I put in 5 it will make it 51 instead of the result I want of 6. Can anyone help me?

int number;
int outcome;

number = int.Parse(numberInputTextBox.Text);

outcomeLabel.Text = number + 1 .ToString();

Upvotes: 1

Views: 2026

Answers (3)

promanski
promanski

Reputation: 567

number = int.Parse(numberInputTextBox.Text);
outcomeLabel.Text = (number + 1).ToString();

You forgot to add ( ). Your sample was:

1) take 1 and convert to string
2) add number and string

in point 2) the number was casted to string before adding to second string. That's why you got string concatenation "5"+"1"="51" instead of integer sum 5+1=6

Upvotes: 3

qaphla
qaphla

Reputation: 4733

1.ToString() will return a string, which you are then adding the string "5" to, as C# will implicitly cast the number 5 to the string "5" when trying to add it to a string.

You need to first add one, then convert to a string, giving something like this:

outcomeLabel.Text = (number + 1).ToString();

or

int newNumber = number + 1;
outcomeLabel.Text = newNumber.ToString();

Upvotes: 1

bytebender
bytebender

Reputation: 7491

Just add parentheses...

number = int.Parse(numberInputTextBox.Text);

outcomeLabel.Text = (number + 1).ToString();

Upvotes: 0

Related Questions