02 December, 2013

Get display name of enum

Problem:
How to get Display name or Description of Enum.

Solution:
I made on extension helper to get display name or description  of Enum.


Usage:
var weekofday = Days.Sun; 
Console.WriteLine(weekofday.ToDisplayName()); 
Console.WriteLine(weekofday.ToDescription());
 
public enum Days
{
    [Display(Name = "Sunday")]
    [Description("First day of week.")]
    Sun,
    [Display(Name = "Monday")]
    Mon,
    [Display(Name = "Tuesday")]
    Tue,
    [Display(Name = "Wednesday")]
    Wed,
    [Display(Name = "Thursday")]
    Thu,
    [Display(Name = "Friday")]
    Fri,
    [Display(Name = "Saturday")]
    Sat
}
 
Output:
Sunday
First day of week. 

Enum Helper:
using System;
using System.Linq;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel;
 
namespace TestWinApp
{
    public static class EnumHelper
    {
        #region Public Method
 
        // This extension method is broken out so you can use a similar pattern with 
        // other MetaData elements in the future. This is your base method for each.
        //In short this is generic method to get any type of attribute.
        public static T GetAttribute<T>(this Enum value) where T : Attribute
        {
            var type = value.GetType();
            var memberInfo = type.GetMember(value.ToString());
            var attributes = memberInfo[0].GetCustomAttributes(typeof(T), false);
            return (T)attributes.FirstOrDefault();//attributes.Length > 0 ? (T)attributes[0] : null;
        }
 
        // This method creates a specific call to the above method, requesting the
        // Display MetaData attribute.
        //e.g. [Display(Name = "Sunday")]
        public static string ToDisplayName(this Enum value)
        {
            var attribute = value.GetAttribute<DisplayAttribute>();
            return attribute == null ? value.ToString() : attribute.Name;
        }
 
        // This method creates a specific call to the above method, requesting the
        // Description MetaData attribute.
        //e.g. [Description("Day of week. Sunday")]
        public static string ToDescription(this Enum value)
        {
            var attribute = value.GetAttribute<DescriptionAttribute>();
            return attribute == null ? value.ToString() : attribute.Description;
        }
 
        #endregion
    }
}

No comments:

Post a Comment