Posts Tagged With ‘String Field&8217


How to retrieve String from Enum in C#

Below is an example of EnumUtils Class. Which can be used to retrieve string value of any enum

    
  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.");
        }
    }

Now, define some enums to test.

    
    public enum SignOnDetails
    {
       [DescriptionAttribute("john")]                 userName,
       [DescriptionAttribute("12DJohnIekls")]         password
    }

Now retrieve those enums string field using EnumUtils we have already created:

     
    public enum signOnDetails
    {
     System.out.println(EnumUtils.stringValueOf(SignOnDetails.userName)); // will print john
     System.out.println(EnumUtils.stringValueOf(SignOnDetails.password)); // will print 12DJohnIekls
    }