Last active
December 21, 2015 18:59
-
-
Save danielmackay/6350828 to your computer and use it in GitHub Desktop.
Helper functions for pulling attributes from enums. #enum
This file contains hidden or 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
/// <summary> | |
/// A helper class which helps conversion between enum and code. | |
/// </summary> | |
public static class EnumExt | |
{ | |
/// <summary> | |
/// Get a description of Enum | |
/// </summary> | |
/// <param name="value">Enum value</param> | |
/// <returns>description</returns> | |
public static string GetDescription(this Enum value) | |
{ | |
FieldInfo fieldInfo = value.GetType().GetField(value.ToString()); | |
var attributes = (DescriptionAttribute[])fieldInfo.GetCustomAttributes(typeof(DescriptionAttribute), false); | |
if (attributes.Length > 0) | |
return attributes[0].Description; | |
return value.ToString(); | |
} | |
/// <summary> | |
/// Get a description of Enum | |
/// </summary> | |
/// <param name="value">Enum value</param> | |
/// <returns>description</returns> | |
public static string GetDisplayName(this Enum value) | |
{ | |
FieldInfo fieldInfo = value.GetType().GetField(value.ToString()); | |
var attributes = (DisplayAttribute[])fieldInfo.GetCustomAttributes(typeof(DisplayAttribute), false); | |
if (attributes.Length > 0) | |
return attributes[0].Name; | |
return value.ToString(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment