Descriptive Enums in C#
Easily add descriptive text to enums in C#:
using System;
using System.ComponentModel;
public enum Genre
{
[Description("Acid Jazz")]
AcidJazz,
Metal,
[Description("R&B and Soul")]
RAndBAndSoul
}
You can then access descriptions with an extension method:
using System;
using System.Linq;
using System.Reflection;
public static class Extensions
{
public static string Description(this Enum value)
{
if (value == null)
{
throw new ArgumentNullException("value", "value cannot be null.");
}
string text = value.ToString();
string result = text;
Type type = value.GetType();
MemberInfo info = type.GetMember(text).FirstOrDefault();
if (info != null)
{
DescriptionAttribute da = info.GetCustomAttributes(
typeof(DescriptionAttribute),
false).FirstOrDefault() as DescriptionAttribute;
if (da != null)
{
result = da.Description;
}
}
return result;
}
}
Written by Chad Burggraf
Related protips
Have a fresh tip? Share with Coderwall community!
Post
Post a tip
Best
#C
Authors
Related Tags
#c
Sponsored by #native_company# — Learn More
#native_title#
#native_desc#