Created
January 15, 2015 11:23
-
-
Save maftieu/6cd02e9804c98e8fe87b to your computer and use it in GitHub Desktop.
C# - Extension methods for Enum
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; | |
namespace Untunh.Helpers | |
{ | |
/// <summary> | |
/// Provides a set of static methods for querying objects that represent an enumeration. | |
/// </summary> | |
public static class EnumExtensions | |
{ | |
/// <summary> | |
/// Fetch the description of the <paramref name="enumType"/> enumeration value. | |
/// </summary> | |
/// <param name="enumType">Enumeration value for which to return the description.</param> | |
/// <returns>The description of the provided enumeration value.</returns> | |
public static string Description(this Enum enumType) | |
{ | |
var memInfo = enumType.GetType().GetMember(enumType.ToString()); | |
if (memInfo != null && memInfo.Length > 0) | |
{ | |
object[] attrs = memInfo[0].GetCustomAttributes(typeof(DescriptionAttribute), false); | |
if (attrs != null && attrs.Length > 0) | |
return ((DescriptionAttribute)attrs[0]).Description; | |
} | |
return enumType.ToString(); | |
} | |
/// <summary> | |
/// Indicates wether the <paramref name="enumType"/> enum value has a description. | |
/// </summary> | |
/// <param name="enumType">Enumeration value for which to indicate wether is has a description.</param> | |
/// <returns>true if a description is defined on the enumeration value ; otherwise false.</returns> | |
public static bool HasDescription(this Enum enumType) | |
{ | |
return !string.IsNullOrWhiteSpace(enumType.Description()); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment