0

This is a program I wrote to solve quadratic equations. I have three textboxes for inputting the value of a,b and c. If I use the following code, without assigning any value to a,b or c before the if statement, I get an error "Use of unassigned variable" in the line double Delta = Math.Pow(b, 2) - 4 * a * c;, only regarding variable b and c(not a).

private void bt_Calculate_MouseClick(object sender, MouseEventArgs e)
    {
        Double a, b, c;


        if (txt_b.Text != "" && txt_b.Text != "" && txt_c.Text != ""

         && (Double.TryParse(txt_a.Text, out a) && Double.TryParse(txt_b.Text, out b) && Double.TryParse(txt_c.Text, out c)) == true)

        {

            double Delta = Math.Pow(b, 2) - 4 * a * c;

            if (Delta > 0)
            {
                Double x1 = Math.Round((-b + Math.Sqrt(Delta)) / (2 * a), 4);
                Double x2 = Math.Round((-b - Math.Sqrt(Delta)) / (2 * a), 4);
                txt_Result1.Text = Convert.ToString(x1);
                txt_Result2.Text = Convert.ToString(x2);
            }

            else if (Delta == 0)
            {

                Double x1 = Math.Round(-b / (2 * a), 4);
                txt_Result1.Text = Convert.ToString(x1);
            }

            else
            {
                MessageBox.Show("Impossible Equation.");
            }

        }

        else if ((txt_a.Text == "") || (txt_b.Text == "") || (txt_c.Text == ""))
        {
            MessageBox.Show("Provide a value for a, b and c.");
        }
        else
        {
            MessageBox.Show("Provide a valid number, please");

        }

}

However, the program doesn't give any error and outputs the right result when I assign the value 0 to all three variables before the if statement. As such: Double a=0, b=0, c=0; I would like to know why this happens exactly. Isn't TryParse supposed to store the value in the given variable if it returns true? My program also works if I assign the textboxes content to their respective variable in the beginning of the first if block. For example: txt_a.Text = a.

lepi
  • 5
  • 2
  • also https://stackoverflow.com/questions/8931226/are-c-sharp-uninitialized-variables-dangerous/8933935#8933935 – Crowcoder Oct 02 '18 at 17:08

1 Answers1

2

The compiler just isn't smart enough.

Something like this is totally OK:

double a, b;
if (double.TryParse("5", out a) && double.TryParse("6", out b))
    // works fine
    Console.WriteLine("a = {0}, b = {1}", a, b);

But if we make the conditional statement a little more complex, then suddenly the compiler is no longer sure whether you've initialized the variable or not:

double a, b;
if (true == (double.TryParse("5", out a) && double.TryParse("6", out b)))
    // generates an error
    Console.WriteLine("a = {0}, b = {1}", a, b);

It's perfectly fine to initialize those variables to 0.

RogerN
  • 3,761
  • 11
  • 18