Enum With String Values In C#

Hello again,
 

I am currently making a Virtual Earth asp.net ajax server control and came to the point where I had to replicate the enums in my classes, but the issue with them is that the enums do not use integer values but string ones. In C# you cannot have an enum that has string values :(. So the solution I came up with (I am sure it has been done before) was just to make a new custom attribute called StringValueAttribute and use this to give values in my enum a string based value.

Note: All code here was written using .NET 3.5 and I am using 3.5 specific features like automatic properties and exension methods, this could be rewritten to suit 2.0 quite easily.


First I created the new custom attribute class, the source is below:

    /// <summary>
    /// This attribute is used to represent a string value
    /// for a value in an enum.
    /// </summary>
    public class StringValueAttribute : Attribute {

        #region Properties

        /// <summary>
        /// Holds the stringvalue for a value in an enum.
        /// </summary>
        public string StringValue { get; protected set; }

        #endregion

        #region Constructor

        /// <summary>
        /// Constructor used to init a StringValue Attribute
        /// </summary>
        /// <param name="value"></param>
        public StringValueAttribute(string value) {
            this.StringValue = value;
        }

        #endregion

    }

 
Then I created a new Extension Method which I will use to get the string value for an enums value:

        /// <summary>
        /// Will get the string value for a given enums value, this will
        /// only work if you assign the StringValue attribute to
        /// the items in your enum.
        /// </summary>
        /// <param name="value"></param>
        /// <returns></returns>
        public static string GetStringValue(this Enum value) {
            // Get the type
            Type type = value.GetType();

            // Get fieldinfo for this type
            FieldInfo fieldInfo = type.GetField(value.ToString());

            // Get the stringvalue attributes
            StringValueAttribute[] attribs = fieldInfo.GetCustomAttributes(
                typeof(StringValueAttribute), false) as StringValueAttribute[];

            // Return the first if there was a match.
            return attribs.Length > 0 ? attribs[0].StringValue : null;
        }
 

So now create your enum and add the StringValue attributes to your values:

 public enum Test : int {
        [StringValue("a")]
        Foo = 1,
        [StringValue("b")]
        Something = 2       
 }


Now you are ready to go, to get the string value for a value in the enum you can do so like this now:

Test t = Test.Foo;
string val = t.GetStringValue();

- or even -

string val = Test.Foo.GetStringValue();



All this is very easy to implement and I like the ease of use you get from the extension method [I really like them :)] and it gave me the power I needed to do what I needed. I haven't tested the performance hit that the reflection may give and might do so sometime soon.


Thanks
Stefan

Published Wednesday, March 12, 2008 11:56 PM by stefan.sedich

Comments

# Our daily link (2008-03-12)

Wednesday, March 12, 2008 4:50 PM by Trumpi's blog

SSIS: Populate the Lookup component cache from a flat file Turn Anonymous Types into IDictionary of values

# Reflective Perspective - Chris Alcock &raquo; The Morning Brew #52

Pingback from  Reflective Perspective - Chris Alcock  &raquo; The Morning Brew #52

# re: Enum With String Values In C#

Thursday, March 13, 2008 4:49 AM by Vimpyboy

You can use this attribute for your StringValueAttribute:

[AttributeUsage(AttributeTargets.Field)]

If you have that, you can only use the attribute on the fields in an enum. :-)

# re: Enum With String Values In C#

Thursday, March 13, 2008 7:49 AM by stefan.sedich

Thanks for that mate, could be handy to stop people using it for purposes it is not made to do :P and I am sure it will happen.

Thanks

Stefan

# Dew Drop - March 13, 2008 | Alvin Ashcraft's Morning Dew

Thursday, March 13, 2008 9:00 AM by Dew Drop - March 13, 2008 | Alvin Ashcraft's Morning Dew

Pingback from  Dew Drop - March 13, 2008 | Alvin Ashcraft's Morning Dew

# re: Enum With String Values In C#

Thursday, May 29, 2008 10:33 AM by James Coe

Hi Stefan,

Interesting approach to this. I also faced the same problem a while ago and posted my solution called SpecializedEnum to CodePlex recently. It provides fairly thorough emulation of enum's behaviors with any arbitrary object type.

James.

# re: Enum With String Values In C#

Thursday, June 26, 2008 2:36 PM by Ian

I like this idea.  I do have one question though.  How do you do the reverse?  Using your example, if you load the field from a database, and the field contains "b", how do you set the object property (which is of type Test) to the proper enum value?  In other words, how would you implement the extension method SetValueByString?  I ask because I've tried to do this and have failed so far :(

# re: Enum With String Values In C#

Tuesday, July 08, 2008 8:10 AM by Ian

How do you set the string value?  Ie you read the value "b" from the database and want to set the enum to that value.

Leave a Comment

(required) 
(required) 
(optional)
(required)