Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unassigned variable and "Not all code paths return a value" workaround?

private static char GetGuess()
{ 
    char guess;
    bool guessInputSuccess = false;

    while (!guessInputSuccess)
    { 
        Console.Write("Guess your letter: ");

        char.TryParse(Console.ReadLine().ToLower(), out guess); 

        if (!char.IsLetter(guess))
        { 
            Console.Write("You have not entered a letter from a-z."); 
        }
        else
        { 
            guessInputSuccess = true; 
        } 
    }

    return guess; 
}

As it currently looks, I cannot return guess because it's unassigned. The way I'd usually get around this is by assigning guess to a random character. Since the while loop will continue until a valid character from a-z is input, one could be confident that by the time it returns, a character from a-z will be assigned to guess. I personally don't like this workaround because for me, it feels sloppy.

My question is: Is there any way I can keep guess initialized but unassigned in the beginning of the method and still have it set and returned properly by the end of the methods execution?


1 Answers

Just return as soon as you enter a correct guess - and loop forever until then. You don't need guessInputSuccess at all, and guess can have a smaller scope:

private static char GetGuess()
{ 
    while (true)
    { 
        Console.Write("Guess your letter: ");
        if (char.TryParse(Console.ReadLine().ToLower(), out char guess) && 
            char.IsLetter(guess))
        {
            return guess;
        }
        Console.Write("You have not entered a letter from a-z."); 
    }
}
like image 132
Jon Skeet Avatar answered Apr 14 '26 21:04

Jon Skeet



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!