To make IncreaseStudents
work the way you want, you need to change two things: You need to return a value, meaning it can’t be void
. And you need change the way you turn textBox3.Text
into an integer. You don’t parse the whole expression, textBox3.Text + num
; num
is a number already. All you need (or want) to parse is textBox3.Text
, because it’s a string. And we’ll use a different way of parsing, so that if the text doesn’t represent a number, it will fail politely instead of throwing an exception.
public int IncreaseStudents(int num)
{
int n;
if (int.TryParse(textBox3.Text, out n))
{
return n + num;
}
else
{
MessageBox.Show("Not a number: " + textBox3.Text);
return num;
}
}
Then this line of code should work fine — unless s1._stdNumber
is something weird that you can’t add to.
listBox1.Items.Add(s1._stdNumber + IncreaseStudents(25));
But that’s not the assignment. The assignment says you have to use void. So, another try:
public void IncreaseStudents(int num, out int result)
{
int n;
if (int.TryParse(textBox3.Text, out n))
{
result = n + num;
}
else
{
MessageBox.Show("Not a number: " + textBox3.Text);
result = num;
}
}
And call like this:
int result = 0;
IncreaseStudents(25, out result)
listBox1.Items.Add(s1._stdNumber + result);
Silly, but if your instructor wants that, that’s what he wants.
10
solved Can’t add numbers using the void method