Using EnumMemberAttribute and doing automatic string conversions
c#, enums
Solution
Here is my proposition - it should give you the idea on how to do this (check also Getting attributes of Enum's value):
public static string ToEnumString<T>(T type)
{
var enumType = typeof (T);
var name = Enum.GetName(enumType, type);
var enumMemberAttribute = ((EnumMemberAttribute[])enumType.GetField(name).GetCustomAttributes(typeof(EnumMemberAttribute), true)).Single();
return enumMemberAttribute.Value;
}
public static T ToEnum<T>(string str)
{
var enumType = typeof(T);
foreach (var name in Enum.GetNames(enumType))
{
var enumMemberAttribute = ((EnumMemberAttribute[])enumType.GetField(name).GetCustomAttributes(typeof(EnumMemberAttribute), true)).Single();
if (enumMemberAttribute.Value == str) return (T)Enum.Parse(enumType, name);
}
//throw exception or whatever handling you want or
return default(T);
}
Problem
I have the following code ``` [DataContract] public enum StatusType { [EnumMember(Value = "A")] All, [EnumMember(Value = "I")] InProcess, [EnumMember(Value = "C")] Complete, } ``` I'd like to do the following: ``` var s = "C"; StatusType status = SerializerHelper.ToEnum<StatusType>(s); //status is now StatusType.Complete string newString = SerializerHelper.ToEnumString<StatusType>(status); //newString is now "C" ``` I've done the second part using DataContractSerializer (see code below), but it seems like a lot of work. Am I missing something obvious? Ideas? Thanks. ``` public static string ToEnumString<T>(T type) { string s; using (var ms = new MemoryStream()) { var ser = new DataContractSerializer(typeof(T)); ser.WriteObject(ms, type); ms.Position = 0; var sr = new StreamReader(ms); s = sr.ReadToEnd(); } using (var xml = new XmlTextReader(s, XmlNodeType.Element, null)) { xml.MoveToContent(); xml.Read(); return xml.Value; } } ```