C#: Enums and String Values

One of the biggest things that I've had a problem with C# is its complete, utter lack of string value enumerations.  Enums provide strongly typed domain values that make programming easier to manage.  However, since you can't include characters like wildcards, spaces, etc., this means that making a human readable enum a nearly impossible task.  Until now.  This takes a little more heavy lifting than I come to expect with the .Net framework, but is a relatively easy fix for what you get in return.  This is broken into two parts:
  1. Create the String value for the enum.
  2. Get the value out.

First things first, how to create a string value enum.  To do this we need to import the System.Reflection and System.ComponentModel into the class and to create a new enum as follows:

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

As you can see we define the enum just like we normally do, except we take advantage of C#'s DescriptionAttribute class.   What this does is allows us to bind a string attribute to the enum which normally only accepts  numerical type data.  Unlike other methods to do this, we don't break the enum paradigm.  If I had my druthers I would have liked to inherit from the Enum class itself, but that's not possible.

So, now that we've created our enum, how do we retrieve that value?  Next we create another class as outlined below:

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

What we do in the first method is use reflection to access the DescriptionAttribute that we created when we constructed the enum.  If the enum value doesn't have a DescriptionAttribute associated with it, we return the ToString() value of the enum itslef.  That way, enums like 'Vanilla' get returned as "Vanilla" instead of null.

The second method enumValueOf address the need to go from the string value to the enum itself.  This uses the Enum static methods to compare the string value to the list of enum values.  While this particular could be further optimized with caching, this sets up a basic, but useful string value enumeration.

Enjoy!

Print | posted on Friday, October 05, 2007 7:32 PM

Comments on this post

# re: C#: Enums and String Values

Requesting Gravatar...
Very Nice Work Man I love it


Thank you alot.
Left by Shouha on Jul 22, 2008 4:06 AM

# re: C#: Enums and String Values

Requesting Gravatar...
hey thanks for the great piece of code...it was really helpful for me today...
Left by jonathan parker on Oct 03, 2008 3:54 PM

# re: C#: Enums and String Values

Requesting Gravatar...
Give a example,please!Thanks.
Left by boy on Oct 27, 2008 9:48 PM

# re: C#: Enums and String Values

Requesting Gravatar...
Thanks for posting, Vb.net version of codes i posted below

mefeozer.wordpress.com/.../get-enum-values-as-s...
Left by M.Efe Ozer on Oct 31, 2008 10:09 AM

# re: C#: Enums and String Values

Requesting Gravatar...

I looked all over the internet for a solution such as yours:

Enum.Parse(enumType, name);


Thank you!
Left by Dirk Garner on Dec 09, 2008 12:48 PM

# re: C#: Enums and String Values

Requesting Gravatar...
Thanks for sharing..helped me a lot.
Left by anjee on Dec 12, 2008 1:38 PM

# Help with EnumMemberAttribute? | keyongtech

Requesting Gravatar...
Help with EnumMemberAttribute? | keyongtech
Left by Pingback/TrackBack on Jan 18, 2009 11:24 AM

# re: C#: Enums and String Values

Requesting Gravatar...
Very good post, the best solution I found to this problem!
Left by Bira on Jan 23, 2009 11:56 AM

# re: C#: Enums and String Values

Requesting Gravatar...
very good
Left by a on Feb 11, 2009 7:27 AM

# re: C#: Enums and String Values

Requesting Gravatar...
cool
Left by terry on Apr 30, 2009 2:16 AM

# re: C#: Enums and String Values

Requesting Gravatar...
Why didn't you use Enum.GetValues instead of Enum.GetNames? Then you would have been able to avoid calling Enum.Parse later on.
Left by Tzadik on May 27, 2009 9:45 AM

Your comment:

 (will show your gravatar)
 
Please add 2 and 7 and type the answer here: