I have the following enumeration:
public enum AuthenticationMethod
{
FORMS = 1,
WINDOWSAUTHENTICATION = 2,
SINGLESIGNON = 3
}
The problem however is that I need the word "FORMS" when I ask for AuthenticationMethod.FORMS and not the id 1.
I have found the following solution for this problem (link):
First I need to create a custom attribute called "StringValue":
public class StringValue : System.Attribute
{
private readonly string _value;
public StringValue(string value)
{
_value = value;
}
public string Value
{
get { return _value; }
}
}
Then I can add this attribute to my enumerator:
public enum AuthenticationMethod
{
[StringValue("FORMS")]
FORMS = 1,
[StringValue("WINDOWS")]
WINDOWSAUTHENTICATION = 2,
[StringValue("SSO")]
SINGLESIGNON = 3
}
And of course I 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 I've got the tools to get a string value for an enumerator. I can then use it like this:
string valueOfAuthenticationMethod = StringEnum.GetStringValue(AuthenticationMethod.FORMS);
Okay now all of these work like a charm but I find it a whole lot of work. I was wondering if there is a better solution for this.
I also tried something with a dictionary and static properties but that wasn't better either.
Use method
as in (Assume
Shipper
is a defined Enum)There are a bunch of other static methods on the Enum class worth investigating too...
Just use the
ToString()
methodTo reference the string
Tomato
, just useI use the Description attribute from the System.ComponentModel namespace. Simply decorate the enum and then use this code to retrieve it:
As an example:
This code nicely caters for enums where you don't need a "Friendly name" and will return just the .ToString() of the enum.
for me, the pragmatic approach is class inside class, sample:
How I solved this as an extension method:
Enum:
Usage (where o.OrderType is a property with the same name as the enum):
Which gives me a string of "New Card" or "Reload" instead of the actual enum value NewCard and Refill.
I use an extension method:
Now decorate the
enum
with:When you call
AuthenticationMethod.FORMS.ToDescription()
you will get"FORMS"
.