1

I've a got an Enum that looks like so:

 public enum Month 
    {
        January, February, March,
        April, May, June, July, August,
        Septemper, October, November, December
    };

What I need to really do is ask and read from the user a number also like so:

Console.WriteLine("Enter the number of the 
month")
int monthValue=int.parse(Console.ReadLine())

Lastly I wanna take the monthValue and print the equivalent Enum. (e.g april for monthvalue 4)

Abdul SH
  • 67
  • 7

2 Answers2

3

You can simply cast the value to the enum. Don't forget to set initial value for January or take into account that by default enum starts from 0;

Console application will be next:

class Program
{

    public enum Month
    {
        January, February, March,
        April, May, June, July, August,
        Septemper, October, November, December
    };

    static void Main(string[] args)
    {
        Console.WriteLine("Enter the number of the month");

        int monthValue = 0;
        int.TryParse(Console.ReadLine(), out monthValue);
        Console.WriteLine((Month)monthValue - 1);
        Console.ReadKey();
    }
}

in case you don't need temporary variable you could also really convert it to enum. But not forget to set default enum value

    public enum Month
    {
        January = 1, February, March,
        April, May, June, July, August,
        Septemper, October, November, December
    };

    static void Main(string[] args)
    {
        Console.WriteLine("Enter the number of the month");
        var input = Enum.Parse(typeof(Month), Console.ReadLine());
        Console.WriteLine(input);
        Console.ReadKey();
    }
NILF
  • 367
  • 2
  • 7
  • 1
    Instead of casting the integer to an enum, you can use `Enum.Parse` https://learn.microsoft.com/en-us/dotnet/api/system.enum.parse?view=netframework-4.7.2 – Isitar Nov 21 '18 at 14:24
1

The following code prints the name of the month to the console. It uses the static Enum.GetName()-method for that.

string monthName = Enum.GetName(typeof(Month), monthValue - 1);
Console.WriteLine(monthName);
Stefan Illner
  • 179
  • 1
  • 5
  • 13