Introduction
This helper was written to supply the enum over an Web Api call to list the enum/flags values and display strings, that will still match the code's ordinal value. It was then later used to collect data and seed enum's into the databse.
By setting the DisplayAttribute on the enum and setting the Description property, this helper will assist with getting the "displaystring". This is very handy if you want to use human readable text instead of the ordinal's key.
Used in DbEnum & IDbEnum: https://www.codeproject.com/Reference/1186336/DbEnum
public static class EnumHelper
{
public static IEnumerable<dynamic> GetStruct<TEnum>() where TEnum : struct
{
return (from v in GetPrivateDisplayList<TEnum>()
select new { Id = v, Description = v.ToString() });
}
public static IEnumerable<dynamic> GetDisplayList<TEnum>() where TEnum : struct
{
return (from v in GetPrivateDisplayList<TEnum>()
select new { Id = v, Description = v.GetDisplayString() });
}
public static string GetDisplayString(this Enum source)
{
var da = source.GetDisplayAttribute();
return da != null ? da.Description : source.ToString();
}
private static IEnumerable<Enum> GetPrivateDisplayList<TEnum>() where TEnum : struct
{
var ti = typeof(TEnum).GetTypeInfo();
if (!ti.IsEnum) return null;
return ti.GetEnumValues().Cast<Enum>();
}
private static DisplayAttribute GetDisplayAttribute(this Enum source)
{
var fi = source.GetType().GetTypeInfo().GetField(source.ToString());
return fi.GetCustomAttribute<DisplayAttribute>();
}
}
I am a well seasoned developer with 18 years experience in the industry and have been working on C# since .Net 1 made its debut, which is since 2002 and remember all the hardcore work that needed to be done and has seen how it evolved. I have written multitudes of solutions in .Net for many customers and always learn something new.
Needles to say, my repertoire does not start and end with .Net and includes tech knowledge from database, servers, applications across various streams, not just Microsoft technologies.
In the future I will attempt to hand some of my knowledge down to the community, since it has helped me so many times over the years.