How to take an ENUM constant for the entire value?

Asked

Viewed 2,646 times

1

I have an Enum that represents the months:

public enum Mes
{
    Janeiro,

    Fevereiro,

    Marco,

    ...
}

How do I get the month description for the entire amount? E.g.: Enter with 12 and return December

  • You could distribute numbers associated with each ENUM, it’s one of the best ways, or you could use the ordinal() method to access the constant number, but it’s not very advisable.

2 answers

2


You must assign a whole number to each month, then just perform the conversion.

public enum Mes
{
    Janeiro = 1,

    Fevereiro = 2,

    Marco = 3,

    Dezembro = 12
}

Mes mes = (Mes)12; //mes = Mes.Dezembro

Console.WriteLine(mes); //Dezembro

See working in Dotnetfiddle


Another way is to use a method that is responsible for taking an Enum description. For example in March, it was written as "milestone" to return the name correctly written 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 that way:

Mes mes = (mes)3; //mes = Mes.Marco

ConsoleWriteLine(mes.GetDescription()); //Março

I hope I can help.

0

Browser other questions tagged

You are not signed in. Login or sign up in order to post.