Home > Blockchain >  return function value to variable
return function value to variable

Time:03-07

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;

        }
    }
}


CodePudding user response:

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;

CodePudding user response:

Firstly - you need to initialize the playerName variable (string playerName = "") or (string.Empty)

Second - You're not displaying the playerName, just assigned the result of PlayerName() to the variable. You need to display the variable.

  • Related