Home > .Net > Getting string value from Enum

Getting string value from Enum

Nice article :http://blog.waynehartman.com/articles/84.aspx

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.”);

}

}

———————————————–

public enum ShippingOptions

{

[DescriptionAttribute("2nd Day Air")]

SecondDayAir = 01,

[DescriptionAttribute("Next Day Air")]

NextDayAir = 02,

Ground = 03

}

————————————————

EnumUtils.stringValueOf(Enums.ShippingOptions SecondDayAir)

Answer is : 2nd Day Air

Comments are closed.

TOP