Home > Software design >  while loop with a boolean variable in an int method
while loop with a boolean variable in an int method

Time:10-21

I have written two methods and added an infinite while loop in the method.

  • The first method
    public static int GetNumber()
        {
            bool isCountinue = true;
            while (isCountinue)
            {
                Console.Write("Please enter an integer number: ");
                string value = Console.ReadLine();
                bool isInteger = int.TryParse(value, out int number);
                if (isInteger)
                {
                    return number;
                }
                else
                {
                    Console.WriteLine("Your input is not an integer number!");
                    isCountinue = false;
                }
            }
        }
  • The second method
public static int GetNumber()
    {
        while (true)
        {
            Console.Write("Please enter an integer number: ");
            string value = Console.ReadLine();
            bool isInteger = int.TryParse(value, out int number);
            if (isInteger)
            {
                return number;
            }
            else
            {
                Console.WriteLine("Your input is not an integer number!");
                continue;
            }
        }
    }

I have gotten an error for the first method. Because it is missing the return value in the first method. I am confused why the second method is correct, and the first method is wrong?

CodePudding user response:

Your two methods do two slightly different things, which causes the problem:

Version 1:

When isCountinue is set to false, the while loop will stop running. Control will then pass to the next line after the loop, which is the } denoting the end of the method.

There is no return statement after the end of the loop. That makes the method invalid because it's required to return an int, but in that situation it has nothing to return.

Version 2:

https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/continue says

The continue statement passes control to the next iteration of the enclosing iteration statement in which it appears

This means that when continue is executed, the while loop will run again.

Therefore the only possible exit from the loop - and more importantly, the whole method, is via the return number; line.

That's why the second version of the method compiles, but the first does not. In a non-void method, you must ensure that there is no path to the end of the method which does not involve a return statement.

  •  Tags:  
  • c#
  • Related