简体   繁体   中英

Getting "Use of unassigned local variable" C# error

namespace FirstApp1
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine(GetDay(0));
            Console.ReadLine();
        }
        static string GetDay(int daynum)
        {
            string dayname;
            switch (daynum)
            {
                case 0:
                    dayname = "sunday";
                    break;
            }
            return dayname;
        }

    }
}
static string GetDay(int dayNum) {
  string dayname = String.Empty;
  switch(dayNum) {
   case 0:
    dayname = "sunday";
    break;
  }
  return dayname;
}

Use this line instead:

        string dayname = "";

that way if none of you case statements match, the function can return an empty string;

Otherwise if DayNum != 0, the function has nothing to return - which is why you are getting the error.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM