-
-
Save codehaks/a9a5bf459d248d7493281824ca4929d8 to your computer and use it in GitHub Desktop.
Get Enums "Display" value
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.ComponentModel.DataAnnotations; | |
using System.Linq; | |
namespace Portal.Extentions | |
{ | |
public static class EnumExtentions | |
{ | |
public static string DisplayName(this Enum item) | |
{ | |
var type = item.GetType(); | |
var member = type.GetMember(item.ToString()); | |
DisplayAttribute displayName = (DisplayAttribute)member[0] | |
.GetCustomAttributes(typeof(DisplayAttribute), false) | |
.FirstOrDefault(); | |
if (displayName != null) | |
{ | |
return displayName.Name; | |
} | |
return item.ToString(); | |
} | |
public static string GetDescription(this Enum value) | |
{ | |
var field = value.GetType().GetField(value.ToString()); | |
try | |
{ | |
var attribute | |
= Attribute.GetCustomAttribute(field, typeof(DescriptionAttribute)) | |
as DescriptionAttribute; | |
return attribute == null ? value.ToString() : attribute.Description; | |
} | |
catch (Exception) | |
{ | |
return string.Empty; | |
} | |
} | |
public static string GetValue(this Enum enumItem) | |
{ | |
var value = Convert.ToInt32(enumItem); | |
return value.ToString(); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment