Carter
Carter

Reputation: 3

How do I catch an input that doesn't match my enum parameters

I have here a way of entering in the day of the week, but if I enter in a number value that is not 1-7 the program simply concludes. I want to have a way to trigger the catch.

        namespace DaysOfTheWeek
{
class Program
{
    public enum EDay
    {
        Monday,
        Tuesday,
        Wednesday,
        Thursday,
        Friday,
        Saturday,
        Sunday,
    }
    static void Main(string[] args)
    {
        try
        {
            Console.WriteLine("Hello!  A week has 7 days!  What day of this week is it?");
            EDay pickDay = (EDay)Enum.Parse(typeof(EDay), Console.ReadLine(), true);
            Console.WriteLine("The day you picked was {0}", pickDay - 1);
            Console.ReadLine();
        }
        catch (Exception)
        {
          Console.WriteLine("Please enter an actual numerical day of the week.");
            Console.ReadLine();
        }
    }

}

}

Upvotes: 0

Views: 928

Answers (3)

Kevin Suarez
Kevin Suarez

Reputation: 71

You'll likely want to read what they have input first before converting it into your enum.

Here is a simple example:

try
{
    Console.WriteLine("Hello!  A week has 7 days!  What day of this week is it?");
    var dayEntered = Console.ReadLine();
    int dayInt;
    bool success = int.TryParse(dayEntered, dayInt);
    if(!success || dayInt < (int)EDay.Monday || dayInt > (int)EDay.Sunday)
    {
        //either throw a new exception to go into your catch block or just have logic here.
    }
    EDay pickDay = (EDay)dayInt;
    Console.WriteLine("The day you picked was {0}", pickDay - 1);
    Console.ReadLine();
}
catch (Exception)
{
    Console.WriteLine("Please enter an actual numerical day of the week.");
    Console.ReadLine();
}

Upvotes: 0

Xiaoy312
Xiaoy312

Reputation: 14477

You should use int.Parse if the input is expected to be "numerical". And, int.TryParse will help you catch no-numerical input:

var input = Console.ReadLine();
if (int.TryParse(input, out var value))
{
    if (1 <= value && value <= 7)
    {
        Console.WriteLine("The day you picked was {0}", (EDay)value - 1);
    }
    else
    {
        Console.WriteLine("PLease enter an number between 1 - 7");
    }
}
else
{
    Console.WriteLine("Please enter an actual numerical day of the week.");
}

You can also use Enum.TryParse if you also want to accept input like "monday" with addition to the numerical value. Just make sure to change this line if you want 1 to map to Monday:

Monday = 1,

You can also use (EDay)value directly if you made the above change for the int.TryParse solution.

Upvotes: 1

Rahul
Rahul

Reputation: 77896

You can use IsDefined() like

if(Enum.IsDefined(typeof(EDay), Convert.ToInt32(Console.ReadLine())))

Upvotes: 1

Related Questions