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.