Hi,

Recently I needed a enumeration in my application but at the same time I wanted to be able to print a value of the enumeration in my application.
My enumeration looked like this:

public enum AuthenticationMethod
{
        FORMS = 1,
        WINDOWSAUTHENTICATION = 2,
        SINGLESIGNON = 3
}

Ok so now we could have just used the following code to display the enumeration:

AuthenticationMethod x = AuthenticationMethod.WINDOWSAUTHENTICATION ;
string s = Enum.GetName(typeof(AuthenticationMethod ), x);

But the problem was that the printed text was “WINDOWSAUTHENTICATION” …
So that’s not really what we want, do we? We just want to print: “Windows Authentication”.

So here is how you solve this problem.

First we need to create a custom attribute called “StringValue”:

public class StringValue : System.Attribute
{
        private string _value;

        public StringValue(string value)
        {
                _value = value;
        }

        public string Value
        {
                get { return _value; }
        }
}

Then we can add this attribute to our enumeration:

public enum AuthenticationMethod
{
        [StringValue("FORMS")]
        FORMS = 1,
        [StringValue("WINDOWS")]
        WINDOWSAUTHENTICATION = 2,
        [StringValue("SSO")]
        SINGLESIGNON = 3
}

And off course we need something to retrieve that StringValue:

public static class StringEnum
{
        public static string GetStringValue(Enum value)
        {
                string output = null;
                Type type = value.GetType();

                //Check first in our cached results...

                //Look for our 'StringValueAttribute'

                //in the field's custom attributes

                FieldInfo fi = type.GetField(value.ToString());
                StringValue[] attrs =
                   fi.GetCustomAttributes(typeof(StringValue),
                                                                   false) as StringValue[];
                if (attrs.Length > 0)
                {
                        output = attrs[0].Value;
                }

                return output;
        }
}

Good now We’ve got the tools to get a string value for an enumeration. We can then use it like this:

string valueOfAuthenticationMethod = StringEnum.GetStringValue(AuthenticationMethod.FORMS);

I hope you’ve found what you were looking for.

Cheers,
Mayiko