Friday, October 18, 2013

Enum with String Value Tagging

I have an requirement where I need to get a string value from Enum like KeyValue mapping. Below is the process to use Enum like a KeyValue mapping and get the keyvalue passing enum name . using System.Reflection; Declare a custom class. [AttributeUsage( AttributeTargets.Field )] public sealed class StringValueAttribute : Attribute { private string _value; public StringValueAttribute(string value) { _value = value; } public string Value { get { return _value; } } } Enum declaration. public enum TimezoneName { [StringValueAttribute("Singapore Standard Time")] Asia = 1, [StringValueAttribute("W. Europe Standard Time")] Geneva = 2, [StringValueAttribute("Central Standard Time")] Hoston = 3, [StringValueAttribute("None")] None = 0 } Get string value from Enum. public static string GetEnumStringValue(Enum evalue) { string output = null; if (evalue != null) { Type type = evalue.GetType(); FieldInfo fi = type.GetField(evalue.ToString()); StringValueAttribute[] attrs =fi.GetCustomAttributes(typeof(StringValueAttribute),false) as StringValueAttribute[]; if (attrs.Length > 0) { output = attrs[0].Value; } } return output; }

No comments: