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

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

    In case s.ToLower() is something else that dog, cat or rabbit, animal has no value.

    You should add default in your switch for that case:

    switch (s.ToLower())
    {
    case "dog":
        animal = AnimalTypeEnum.DOG;
        break;
    case "cat":
        animal = AnimalTypeEnum.CAT;
        break;
    case "rabbit":
        animal = AnimalTypeEnum.RABBIT;
        break;
    default:
        animal = ...
        break;
    }
    

提交回复
热议问题