Created
September 4, 2014 20:43
-
-
Save kmoormann/98406999a05e10b8bb11 to your computer and use it in GitHub Desktop.
An extension method for C# that will prove a DisplayNameAttribute if available
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.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