Last active
April 12, 2023 19:04
-
-
Save pedrovasconcellos/b196ece2f226645b2f7202f88176b512 to your computer and use it in GitHub Desktop.
EnumExtension with GetDescription
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using System.ComponentModel; | |
using System.Linq; | |
using System.Reflection; | |
public static class EnumExtension | |
{ | |
public static string GetDescription<TEnum>(this TEnum value) where TEnum : Enum | |
{ | |
FieldInfo fieldInfo = value.GetType().GetField(value.ToString()); | |
DescriptionAttribute[] attributes = fieldInfo | |
.GetCustomAttributes(typeof(DescriptionAttribute), false) as DescriptionAttribute[]; | |
if (attributes != null && attributes.Any()) | |
{ | |
return attributes.First().Description; | |
} | |
return value.ToString(); | |
} | |
public static IList<EnumeratorModel> EnumToDictonary<T>() where T : struct | |
{ | |
if (!typeof(T).IsEnum) throw new ArgumentException($"{typeof(T)} is not an Enum type"); | |
var enumerators = new List<EnumeratorModel>(); | |
var enums = Enum.GetValues(typeof(T)); | |
foreach (var enumItem in enums) | |
{ | |
enumerators.Add(new EnumeratorModel() | |
{ | |
Id = (int)enumItem, | |
Name = enumItem.ToString() | |
}); | |
} | |
return enumerators; | |
} | |
} | |
public enum AnimalsEnum : int | |
{ | |
[Description("Gato")] | |
Cat, | |
[Description("Cachorro")] | |
Dog, | |
} | |
public class EnumeratorModel | |
{ | |
public int Id { get; set; } | |
public string Name { get; set; } | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment