== Enum ==
To declare an enumerated type:
public enum TMyColor
{
Red,
Green,
Blue
}
To convert an enum value to string:
public string GetEnumString(TMyColor obj)
{
return Enum.GetName(typeof(TMyColor), obj);
}
To convert a string into an enum:
TMyColor mycolor = (TMyColor)Enum.Parse(typeof(TMyColor), "Red");
== Enum with Description ==
public enum TMyColor
{
[Description("Red Color")]
Red,
[Description("Green Color")]
Green,
[Description("Blue Color")]
Blue
}
To simply get the enum string equivalent (translate value into string):
//----------------------------------------------------------------------------------------
// Get enum string for the specified object.
//----------------------------------------------------------------------------------------
public static string GetEnumString(TMyColorobj)
{
return Enum.GetName(typeof(TMyColor), obj);
}
To query an enum value for its description:
using System.ComponentModel;
...
//----------------------------------------------------------------------------------------
// Get enum description string for the specified object.
//----------------------------------------------------------------------------------------
public static string GetEnumDescription(Enum value)
{
System.Reflection.FieldInfo fi = value.GetType().GetField(value.ToString());
DescriptionAttribute[] attributes = (DescriptionAttribute[])fi.GetCustomAttributes(typeof(DescriptionAttribute), false);
if ((attributes != null) && (attributes.Length > 0))
{
return attributes[0].Description;
}
else
{
return value.ToString();
}
}
== Enumerate Enum for creating ListBox ==
///----------------------------------------------------------------------------------------
///
/// Enumerate enums to easily create a drop down list based on an enum.
/// Source: http://blog.spontaneouspublicity.com/post/2008/01/17/Associating-Strings-with-enums-in-C.aspx
///
/// Example:
/// DropDownList stateDropDown = new DropDownList();
/// foreach (States state in EnumToList())
/// {
/// stateDropDown.Items.Add(GetEnumDescription(state));
/// }
///
///
///
///----------------------------------------------------------------------------------------
public static IEnumerable EnumToList()
{
Type enumType = typeof(T);
// Can't use generic type constraints on value types,
// so have to do check like this
if (enumType.BaseType != typeof(Enum))
{
throw new ArgumentException("T must be of type System.Enum");
}
Array enumValArray = Enum.GetValues(enumType);
List enumValList = new List(enumValArray.Length);
foreach (int val in enumValArray)
{
enumValList.Add((T)Enum.Parse(enumType, val.ToString()));
}
return enumValList;
}