How to retrieve the description of an enumerator?

5

I have the following enumerator

public enum MeuEnumerador
{
    [Description("Descrição do item do enumerador")]
    Enumerador1 = 1,
    [Description("Outra descrição")]
    Enumerador2 = 2
}

How do I get the value that is in the Description of the enumerator?

    
asked by anonymous 20.11.2015 / 19:56

2 answers

4

I found a solution creating the following extensions for type Enum

public static T ObterAtributoDoTipo<T>(this Enum valorEnum) where T : System.Attribute
{
    var type = valorEnum.GetType();
    var memInfo = type.GetMember(valorEnum.ToString());
    var attributes = memInfo[0].GetCustomAttributes(typeof(T), false);
    return (attributes.Length > 0) ? (T)attributes[0] : null;
}

public static string ObterDescricao(this Enum valorEnum)
{
    return valorEnum.ObterAtributoDoTipo<DescriptionAttribute>().Description;
}

Where the ObterAtributoDoTipo<T> extension will return the attribute that is requested, in this case the Description . Example usage:

var meuEnumerador = MeuEnumerador.Enumerador1;
Attribute atributo = meuEnumerador.ObterAtributoDoTipo<DescriptionAttribute>();

And the extension ObterDescrição will actually return me to Description and for this it uses the other extension to fetch the attribute. Example usage:

var meuEnumerador = MeuEnumerador.Enumerador1;
string descricao = meuEnumerador.ObterDescricao();

I looked in various places on how to do it, and that was the best solution I found, if anyone knows other ways to do this, share it on the answers.

    
20.11.2015 / 19:56
0

just use getDescription:

var teste = MeuEnumerador.GetDescription();
    
07.08.2018 / 20:30