Skip to content

Instantly share code, notes, and snippets.

@kmoormann
Created September 4, 2014 20:43
Show Gist options
  • Save kmoormann/98406999a05e10b8bb11 to your computer and use it in GitHub Desktop.
Save kmoormann/98406999a05e10b8bb11 to your computer and use it in GitHub Desktop.
An extension method for C# that will prove a DisplayNameAttribute if available
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
namespace Inventory.Data {
public static class EnumExtensions {
public static string GetDescription( this Enum currentEnum ) {
var fi = currentEnum.GetType().
GetField( currentEnum.ToString() );
var da = (DescriptionAttribute)Attribute.GetCustomAttribute( fi,
typeof( DescriptionAttribute ) );
var description = da != null ? da.Description : currentEnum.ToString();
return description;
}
public static string GetDisplayName( this Enum currentEnum ) {
var fi = currentEnum.GetType().
GetField( currentEnum.ToString() );
var da = (DisplayNameAttribute)Attribute.GetCustomAttribute( fi,
typeof( DisplayNameAttribute ) );
var displayname = da != null ? da.DisplayName : currentEnum.ToString();
return displayname;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment