0

My code is the following:

        private void btn3_Click(object sender, EventArgs e)
    {
        double income, tax;
        String strOutput = "Total Income = {0,2:n2} Tax = {1,3:c2}";
        income = double.Parse(textBox1.Text);
        if (income < 20000)
        {
            tax = (income * 0.02);
        }
        else if (income < 50000)
        {
            tax = 400 + (income * 0.04);
        }
        else if (income < 100000)
        {
            tax = 1400 + (income * 0.05);
        }
        else if (income < 250000)
        {
            tax = 3900 + (income * 0.10);
        }
        else if (income >= 250000)
        {
            tax = 18900 + (income * 0.20);
        }
        lstOutput.Items.Add(string.Format(strOutput, income, tax));
    }

On the last line i am getting an error of "use of unassigned local variable tax". How do i fix it and why is it happening?

Alexei Levenkov
  • 98,904
  • 14
  • 127
  • 179
YungAsiago
  • 11
  • 2
  • 2
    The compiler can't tell that any of the `if` statements will be executed, and if none are then `tax` never gets initialized. If you put `tax = 0;` before the `income =` line, the error should go away. – Ken White Mar 08 '20 at 05:47
  • I actually understand the OP's confusion, since a number is always either less than or equal to or greater than 250000. But the compiler isn't that smart. – Poul Bak Mar 08 '20 at 06:43

0 Answers0