Skip to content

Instantly share code, notes, and snippets.

@codehaks
Created January 28, 2018 18:34
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save codehaks/a9a5bf459d248d7493281824ca4929d8 to your computer and use it in GitHub Desktop.
Save codehaks/a9a5bf459d248d7493281824ca4929d8 to your computer and use it in GitHub Desktop.
Get Enums "Display" value
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