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

前端 未结 4 926
天命终不由人
天命终不由人 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:56

    You should have a default ENUM for any animal unknown to your code. You could even make your code to learn new animals. For instance.

    switch (s.ToLower())
    {
    default:
        animal = AnimalType.Unkown;
        break;
    }
    

    or

    default:
        animal = new MakeEnum(s.ToLower());
        myEnumList.Add(animal);
        break;
    

    Your MakeEnum basically just needs to check length of current number of enums, and make a new enum using the number or some other parameter.

提交回复
热议问题