I have the following C# code:
AnimalTypeEnum animal;
string s = Console.ReadLine();
switch (s.ToLower())
{
case \"dog\":
animal = AnimalTypeEnum.DOG;
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.
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.
AnimalTypeEnum animal;
var s = Console.ReadLine();
Console.WriteLine(!Enum.TryParse(s, true, out animal) ? "Not a valid animal" : animal.ToString());
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;
}