Home > Software design >  How do you get a specific item in an enumeration by a variable integer in c#?
How do you get a specific item in an enumeration by a variable integer in c#?

Time:02-27

I have this enumeration list

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

I am gathering an integer from the console named input with a value of 1-12. How do I make it print out the corresponding month? Eg:1 = January, 6=June.

Thank you for your time and help!

CodePudding user response:

I invite you to read the documentation about enums

And here is the answer to your question :

var input = Console.ReadLine();
int enumIntValue = int.Parse(input); // You can also use TryParse (safer).
Month month = (Month) enumIntValue; // You can use Enum.IsDefined before to check if the int value is valid for the enum. 
Console.WriteLine(month); // print out the month.

Read also : TryParse, Enum.IsDefined

CodePudding user response:

For information purposes, to see all of the textual values in an enum, you can get the values like so ...

static void Main(string[] args)
{
    var enumValues = Enum.GetValues(typeof(Month));

    foreach (var enumValue in enumValues)
        Console.WriteLine(enumValue);
}

CodePudding user response:

You can convert the integer value to the corresponding Enum via a cast, and then get its string representation:

var monthEnum = (Month)yourIntValue;
var strEnum = monthEnum.ToString();

Note that if yourIntValue isn't a valid enum value (e.g. 0, or 13), then the program will still run, but will output the integer value.

Also note that a better way to get a month's name would be to use the CultureInfo class:

// the current culture info, from your computer
var culture = CultureInfo.CurrentCulture; 

// you can also specify a known culture 
culture = CultureInfo.GetCultureInfo("en")
var monthName = culture.DateTimeFormat.GetMonthName(yourIntValue);

CodePudding user response:

You can cast the int to your Enum

var m = (Month)1;

Console.WriteLine(m.ToString());

But bear in mind if the enum value isn't defined it will simply print the int.

Alternatively you can use

var m = Enum.GetName(typeof(Month), 1);

which will return null if it isn't defined

CodePudding user response:

var input= Console.ReadLine();
Month month = 0;
if (Enum.TryParse(input, out month)) //Using try parse is safer
{
Console.WriteLine(month.ToString());
}
  • Related