Home > OS >  Use of unassigned variable error when I am trying to assign values to variables using IF statements
Use of unassigned variable error when I am trying to assign values to variables using IF statements

Time:04-16

I am writing a program in Windows Forms which I am trying to assign values to variables using IF statements depending on which radiobuttons in the form are clicked. I am getting an error "use of unassigned variable" on the lines below in bold. The issue is that TotalWeeks has apparently not been assigned, however I assigned it a value in the IF statement above that one. Can anyone suggest a possible fix or idea to try and sort out the issue?

private void button1_Click(object sender, EventArgs e)
{
    //Assigning variables
    int WeeklyRate; //To assign integer values for "WeeklyRate" for future calculation use. If Radio button clicked it has value of radio button etc. 
    if (radioButton1.Checked)
    {
        WeeklyRate = 10;
    }
    else if (radioButton2.Checked)
    {
        WeeklyRate = 15;
    }
    else if (radioButton3.Checked)
    {
        WeeklyRate = 20;
    }

    int TotalWeeks;//assign values to total weeks based on number of months selected, to use in calculations for total cost.
    if (radioButton4.Checked)
    {
        TotalWeeks = 12;
    }
    else if (radioButton5.Checked)
    {
        TotalWeeks = 52;
    }
    else if (radioButton6.Checked)
    {
        TotalWeeks = 104;
    }

    int Payments;//assigning the amount of payments based on frequency radiobutton selected. 
    if (radioButton7.Checked)
    {
        **Payments = TotalWeeks;**
    }
    else if (radioButton8.Checked)
    {
        **Payments = TotalWeeks / 4;**
    }
}
}
}

CodePudding user response:

When neither of radioButton4, radioButton5, radioButton6 is checked, then you can't for example divide it by 4.

You should use this when initializing variable

int TotalWeeks = 0;

(result: Payments will be 0 when radioButtons aren't checked)


or this when initializing

int TotalWeeks = null;

and this when assigning the amount of payments

if (radioButton7.Checked && TotalWeeks is not null)
{
    Payments = TotalWeeks;
}
else if (radioButton8.Checked && TotalWeeks is not null)
{
    Payments = TotalWeeks / 4;
}

(result: Now Payments variable is unassigned, when radioButtons aren't checked)

  • Related