Good ole String Enums..

I know, kind of a misnomer, when was String enum a part of a language any way? Good ole here means, I been looking for this stuff since long time. Still it is not a part of C# 4.0 either.. I thought it was, when I looked at the EnumMember attribute but that is more for serialization stuff.. So, for now I just have to create my own infrastructure…

1. Create an Attribute

public class StringValueAttribute : Attribute
    {
        public string StringValueForEnumMember { get; set; }

        public StringValueAttribute(string stringValueForEnumMember)
        {
            StringValueForEnumMember = stringValueForEnumMember;
        }
    }

2. Look for the attribute

  public static class EnumExtensions
    {
        public static string StringValue<T>(this T enumerationValue) where T : struct
        {
            Type type = enumerationValue.GetType();
            if (!type.IsEnum)
                throw new ArgumentException("EnumerationValue must be of Enum type", "enumerationValue");

            //Tries to find a DescriptionAttribute for a potential friendly name
            //for the enum
            MemberInfo[] memberInfo = type.GetMember(enumerationValue.ToString());
            if (memberInfo != null && memberInfo.Length > 0)
            {
                object[] attrs = memberInfo[0].GetCustomAttributes(typeof(StringValueAttribute), false);

                if (attrs != null && attrs.Length > 0)
                {
                    //Pull out the description value
                    return ((StringValueAttribute)attrs[0]).StringValueForEnumMember;
                }
            }
            //If we have no description attribute, just return the ToString of the enum
            return enumerationValue.ToString();
        }
    }

3. Use the attribute

        enum Items
        {
            [StringValue("ItemString")]
            Item
        }

 

Console.WriteLine(Items.Item.StringValue());

Advertisements

About vijayvepa

I'm a software consultant for Software Specialists Inc. currently working at Philips Respironics, Pittsburgh

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: