Search code examples
c#type-conversiontryparse

String is considered 'bool' after TryParse to int


I'm trying to convert a text input into an int that I can multiply and display the product, but whenever I try to parse the textbox contents as int, I get the "cannot convert bool to int" error message. Code is as follows:

private void button2_Click_1(object sender, EventArgs e)
{
    int Int1;
    int Int2;
    int Product;
    string Text1;
    string Text2;
    Text2 = textBox2.Text;
    Text1 = textBox1.Text;
    Int1 = int.TryParse(Text1, out Int1);
    Int2 = int.TryParse(Text2, out Int2);
    Product = Int1 * Int2;
    listBox1.Items.Add(textBox1.Text);
    listBox1.Items.Add(textBox2.Text);
    listBox1.Items.Add(Product);
}

Don't see where I'm going wrong.


Solution

  • This is happening because TryParse returns a bool the result is in the parameter with out, to solve you can remove the attribution.

    int.TryParse(Text1, out Int1);
    int.TryParse(Text2, out Int2);
    Product = Int1 * Int2;
    

    If you using TryParse you should use in a if to check if everything goes with success.

    if(int.TryParse(Text1, out Int1) &&  int.TryParse(Text2, out Int2))
    {        
        Product = Int1 * Int2;
        listBox1.Items.Add(textBox1.Text);
        listBox1.Items.Add(textBox2.Text);
        listBox1.Items.Add(Product);
    }
    

    If you don't need this behavior, you should consider using Parse, because it returns the parsed value.

    Int1 = int.Parse(Text1);
    Int2 = int.Parse(Text2);
    Product = Int1 * Int2;