-2

i encountered an error "Use of unassigned variable 'attempt'" when i run the code below, i don't understand the reason because as i understand the try statement block always runs so the variable should be assigned by the user ? Or am i wrong ? If anyone has i fix or work around that would be helpful.

static void MagicNumber(int rndMin, int rndMax, int lives = 4)
{
    Random rnd = new Random();
    int rndNum = rnd.Next(rndMin, rndMax);
    int attempt;
    do
    {
        try
        {
            Console.WriteLine($"Remaining lives : {lives}");
            Console.WriteLine($"Enter a number between {rndMin} and {rndMax} :");
            attempt = int.Parse(Console.ReadLine());

        }
        catch
        {
            Console.WriteLine("Error : Enter a number !");
        }
    } while ((lives > 0) || (attempt < rndMin) || (attempt > rndMax));
}

MagicNumber(1, 40, 5);
Ayoub
  • 3
  • 1

2 Answers2

3

The variable attempt will not get assigned a value if an exception gets thrown in your try block, so will be unassigned when it gets to the evaluation in your while. The two possible solutions are:

  1. Initialize it to a default value when you declare it.
  2. Assign it some value in your catch block.

Either one should work.

Pierre Plourde
  • 708
  • 4
  • 12
2

An exception can be thrown in the try block prior to setting a value for attempt. You handle the exception so it's then possible for attempt to be referenced before being assigned a value.

Best practice is to always assign an initial value to variables.

Moho
  • 15,457
  • 1
  • 30
  • 31