I've enhanced this answer to give you a more fully rounded-out solution, with better semantic syntax.
using System;
using System.ComponentModel;
public static class EnumExtensions {
// 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.
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[0];
}
// This method creates a specific call to the above method, requesting the
// Description MetaData attribute.
public static string ToName(this Enum value) {
var attribute = value.GetAttribute<DescriptionAttribute>();
return attribute == null ? value.ToString() : attribute.Description;
}
}
This solution creates a pair of extension methods on Enum, to allow you to do what you're looking for. I've enhanced your Enum
code slightly, to use the syntax for the DisplayAttribute
class of System.ComponentModel.DataAnnotations
.
using System.ComponentModel.DataAnnotations;
public enum Days {
[Display(Name = "Sunday")]
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
}
To use the above extension method, you would now simply call the following:
Console.WriteLine(Days.Mon.ToName());
or
var day = Days.Mon;
Console.WriteLine(day.ToName());