“Use of unassigned local variable” compiler error for switch statement in C#?

前端 未结 4 966
天命终不由人
天命终不由人 2021-01-17 06:11

I have the following C# code:

AnimalTypeEnum animal;
string s = Console.ReadLine();
switch (s.ToLower())
{
case \"dog\":
    animal = AnimalTypeEnum.DOG;
            


        
4条回答
  •  孤独总比滥情好
    2021-01-17 06:48

    Here's one way to fix it, using recursive calls instead of needing to catch and throw exceptions, or use a loop (loops in a case like this obfuscate the meaning in my opinion; too much about how you're doing it instead of what you're doing):

    private static AnimalTypeEnum GetAnimalFromInput()
    {
        AnimalTypeEnum animal;
        string s = Console.ReadLine();
        switch (s.ToLower())
        {
            case "dog":
                animal = AnimalTypeEnum.DOG;
                break;
            case "cat":
                animal = AnimalTypeEnum.CAT;
                break;
            case "rabbit":
                animal = AnimalTypeEnum.RABBIT;
                break;
            default:
                Console.WriteLine(s + " is not valid, please try again");
                animal = GetAnimalFromInput();
                break;
        }
        return animal;
    }
    static void Main(string[] args)
    {
        AnimalTypeEnum animal = GetAnimalFromInput();
    
        Console.WriteLine(animal);
    }
    

    I'll also note that it's good practice to refactor your switch into an if/else chain, using if (s.Equals("dog", StringComparison.CurrentCultureIgnoreCase)) (or the appropriate case-insensitive comparison) to keep it working in other cultures. Of course, this may not apply to your scenario (e.g. test/homework app, or something that will only possibly be used in your culture).


    Update: Thanks to Mennan Kara for the idea, if your values (e.g. "dog") will always match the enum's values (e.g. DOG), then you can use Enum.TryParse to improve your code:

    private static AnimalTypeEnum GetAnimalFromInput()
    {
        AnimalTypeEnum animal;
        string s = Console.ReadLine();
        if (Enum.TryParse(s, true, out animal))
            return animal;
        else
        {
            Console.WriteLine(s + " is not valid, please try again");
            return GetAnimalFromInput();
        }
    }
    

    If you need the flexibility of having them separate, then keep your existing switch.

提交回复
热议问题