[SOLVED] return function value to variable

Issue

I’m trying to understand c# and methods/functions at the moment.
I simply want to have the function PlayerName() return a value that can be stored in the variable playerName.
I have this piece of code and I don’t understand what is wrong.
Without the while-loop, it works. As soon as the while loop is implemented, however, a problem occurs in return playerName (Use of unassigned local variable ‘playerName’). I don’t understand how it is unassigned.


namespace methodtest
{
    internal class Program
    {
        static void Main(string[] args)
        {
            string playerName = PlayerName();

        }

        static string PlayerName()
        {
            bool notCorrect = true;
            string playerName;
            while (notCorrect)
            {
                Console.Write("Type your name: ");
                playerName = Console.ReadLine();
                Console.WriteLine($"You typed {playerName}. Continue? 'y'/'n'");
                string correct = Console.ReadLine();

                if (correct == "n")
                {
                    Console.WriteLine("Try again.");
                }
                else if (correct == "y")
                {
                    notCorrect = false;
                }
            }
            return playerName;

        }
    }
}


Solution

The error message you’re getting is CS0165: Use of unassigned local variable 'playerName'
The compiler is telling you that you need to give playerName an initial value.
You can initialize it with any of the following you seem fit.

string.Empty or ""

null

as an example
string playerName = string.Empty;

Answered By – Snazzie

Answer Checked By – Jay B. (BugsFixing Admin)

Leave a Reply

Your email address will not be published.