Created
March 29, 2015 17:39
-
-
Save digitaldrummerj/56c2510afb0d43f89fb9 to your computer and use it in GitHub Desktop.
Enum Utilities
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
***** For Enums ADD Description attribute to each enum and using statement to class with enum | |
using System.ComponentModel; | |
[Description("Admin")] | |
**************** | |
CLASS TO GET ENUM INTO NAME/VALUE Dictionary to use for DataBinding | |
using System; | |
using System.Collections.Generic; | |
using System.ComponentModel; | |
usingFor Enums System.Reflection; | |
using System.ComponentModel; | |
public class EnumUtilities | |
{ | |
/// <summary> | |
/// Gets the enum pairs. | |
/// </summary> | |
/// <param name="type">The enum type.</param> | |
/// <returns><see cref="Dictionary{TKey,TValue}"/> for the enum pairs.</returns> | |
public static Dictionary<int, string> GetEnumPairs(Type type) | |
{ | |
if (type == null) | |
{ | |
throw new ArgumentNullException("type"); | |
} | |
if (!type.IsEnum) | |
{ | |
throw new ArgumentException("Only enumeration type is expected."); | |
} | |
Dictionary<int, string> pairs = new Dictionary<int, string>(); | |
foreach (int i in Enum.GetValues(type)) | |
{ | |
pairs.Add(i, GetDescription(type.GetField(Enum.GetName(type, i)))); | |
} | |
return pairs; | |
} | |
/// <summary> | |
/// Gets the description. | |
/// </summary> | |
/// <param name="field">The field.</param> | |
/// <returns>Enum decription or text.</returns> | |
private static string GetDescription(FieldInfo field) | |
{ | |
object[] descriptions = field.GetCustomAttributes(typeof(DescriptionAttribute), false); | |
if (descriptions.Length > 0) | |
{ | |
return ((DescriptionAttribute)descriptions[0]).Description; | |
} | |
return field.Name; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment