Search code examples
c#while-loopscopeouttryparse

Why does my uninitialised variable become unassigned again after it has its value set inside of TryParse?


The variable inputBool is declared outside of a while loop, and then set inside of a while loop when I try to parse userInput to a boolean. Once the while loop is exited though, inputBool becomes undeclared again!

However if I initialize the inputBool variable with a value (EG false) it will get set inside of the while loop and will then stay set to whatever it was assigned to inside of TryParse, even after the while loop is exited.

This is the behavior I want, but why doesn't it work when I don't initialize the variable straight away?

        foreach (string question in questions)
        {
            bool isBool = false;
            // inputBool declared here.
            bool inputBool;
            string userInput;

            while (!isBool)
            {
                Console.WriteLine(question);
                userInput = Console.ReadLine();

                // inputBool gets assigned a value here in the TryParse.
                isBool = Boolean.TryParse(userInput, out inputBool);
                if (!isBool) Console.WriteLine("Please respond with 'true' or 'false'.");
            }

            // inputBool is unassigned here!
            answers[askingIndex] = inputBool;
            askingIndex++;
        }

Solution

  • From a flow analysis standpoint, there is no guarantee that the while loop will get executed at least once. Of course, you know otherwise because your condition involves a bool variable that is initialized to a value of false, but the compiler is not smart enough to realize it.

    Therefore, if it doesn't execute at least once, inputBool will still be unitialized at the end, hence the error.

    You need to ensure the variable is initialized in all code paths. There are two possible fixes:

    1. Change the while to a do...while. That one is guaranteed to execute at least once, which ensures the variable becomes initialized.
    2. Initialize the variable to a sensible default value.