I have an Enum that represents the months:
public enum Mes
{
Janeiro,
Fevereiro,
Marco,
...
}
How do I get the full month's description of the month? Ex: Enter 12 and return December
I have an Enum that represents the months:
public enum Mes
{
Janeiro,
Fevereiro,
Marco,
...
}
How do I get the full month's description of the month? Ex: Enter 12 and return December
You should assign an integer every month, then just convert.
public enum Mes
{
Janeiro = 1,
Fevereiro = 2,
Marco = 3,
Dezembro = 12
}
Mes mes = (Mes)12; //mes = Mes.Dezembro
Console.WriteLine(mes); //Dezembro
See working at DotNetFiddle
Another way is to use a method that is responsible for taking a description of the enum. For example in the month of March, it was written as "milestone" to return the written name correctly add this method to your project:
/// <summary>
/// Método responsável por mostrar o user friendly names dos enums, apenas adicionando [Description("Nome Amigável")] e utilizar enum.GetDescription()
/// </summary>
/// <param name="value">enum</param>
/// <returns>String com o nome do enum</returns>
public static string GetDescription(this Enum value)
{
Type type = value.GetType();
string name = Enum.GetName(type, value);
if (name != null)
{
FieldInfo field = type.GetField(name);
if (field != null)
{
DescriptionAttribute attr = Attribute.GetCustomAttribute(field, typeof(DescriptionAttribute)) as DescriptionAttribute;
if (attr != null)
{
return attr.Description;
}
}
}
return null;
}
And decorate your enum like this:
public enum Mes
{
[Description("Janeiro")]
Janeiro = 1,
[Description("Fevereiro")]
Fevereiro = 2,
[Description("Março")]
Marco = 3,
[Description("Dezembro")]
Dezembro = 12
}
Make the call this way:
Mes mes = (mes)3; //mes = Mes.Marco
ConsoleWriteLine(mes.GetDescription()); //Março
I hope you can help.
I think the intended one will be something of a style:
Mes mesEnum = "Janeiro".ToEnum<Mes>();
This situation can be checked in other discussions.
I found an example in English, but you can check what you find in Portuguese if you look good.