3

I have a problem about some simple code in console. Precisely I created a public enum called Year which contains 4 seasons (obvious). I want the program to ask at the beginning what is the season of the year and then generate an answer to each option. The problem is I don't know how to convert my string input to each option of this enum. Maybe it will be more clear if i show you the code (it's short).

            Console.WriteLine("What time of year is it?");
        var input = Console.ReadLine();

            //earlier it was just
            //time = Year.Winter;

        switch (time)
        {
            case Year.Autumn:
                Console.WriteLine("You're gonna have to grab the leaves");
                break;

            case Year.Summer:
                Console.WriteLine("Let's go to the beach");
                break;

            case Year.Winter:
                Console.WriteLine("Better to warm up at home");
                break;
            case Year.Spring:
                Console.WriteLine("Best time of the year!");
                break;

            default:
                Console.WriteLine("I don't know this time of year");
                break;
        }

I want to make something like this but dunno what to put inside this switch statement because I can't just put there my string 'input'. Is it possible in the way I am thinking of it?

CoderCharmander
  • 1,862
  • 10
  • 18

2 Answers2

1

You can parse a try to parse a string into an Enum by using one of the Enum class.

In particular, you can use the typed method TryParse in this eay

var ignoreCase = true; // decide this
if (Enum.TryParse<MyEnum>("my string", ignoreCase, out var r))
    // use r
else
    Console.WriteLine("Please enter the correct value.");
Yennefer
  • 5,704
  • 7
  • 31
  • 44
0

You can use string contain() function before the switch statment like below i haven't tested if it works like this (nested) if not you have to use if and else if condition

time = input.Trim().Contains("winter") ? Year.Winter: (input.Trim().Contains("summer") ?Year.Summer :(input.Trim().Contains("autumn") ?Year.Autumn:i(nput.Trim().Contains("autumn") ?Year.Autumn: null)));

The other thing you can do is give user option like 1 Year.Autumn,2 Year.Summer,3 Year.Winter,4 Year.Spring and get a number on which you can use the switch statment

Aitezaz Bilal
  • 13
  • 2
  • 5