home screen

Search



Number Of Result : 0

Result :


Monday, May 11, 2009

Enum with String

- First you create a enum:

- 1. Using DescriptionAttribute

public enum IceCream
{
[DescriptionAttribute("Chocolate Chip")]
ChocolateChip,
[ DescriptionAttribute("Rocky Road")]
RockyRoad
}


- 2. Using Reflection

public class EnumUtils
{
public static string stringValueOf(Enum value)
{
FieldInfo fi = value.GetType().GetField(value.ToString());
DescriptionAttribute[] attributes = (DescriptionAttribute[])fi.GetCustomAttributes(typeof(DescriptionAttribute), false);
if (attributes.Length > 0)
{
return attributes[0].Description;
}
else
{
return value.ToString();
}
}

public static object enumValueOf(string value, Type enumType)
{
string[] names = Enum.GetNames(enumType);
foreach (string name in names)
{
if (stringValueOf((Enum)Enum.Parse(enumType, name)).Equals(value))
{
return Enum.Parse(enumType, name);
}
}

throw new ArgumentException("The string is not a description or value of the specified enum.");
}
}


- 3. Apply

string iceCream = EnumUtils.stringValueOf(IceCream. ChocolateChip);
//iceCream variable will be "Chocolate Chip"

No comments: