I have the following enumeration:
public enum AuthenticationMethod
{
FORMS = 1,
WINDOWSAUTHENTICATION = 2,
SINGLESIGNON = 3
}
T
Unfortunately reflection to get attributes on enums is quite slow:
See this question: Anyone know a quick way to get to custom attributes on an enum value?
The .ToString()
is quite slow on enums too.
You can write extension methods for enums though:
public static string GetName( this MyEnum input ) {
switch ( input ) {
case MyEnum.WINDOWSAUTHENTICATION:
return "Windows";
//and so on
}
}
This isn't great, but will be quick and not require the reflection for attributes or field name.
C#6 Update
If you can use C#6 then the new nameof
operator works for enums, so nameof(MyEnum.WINDOWSAUTHENTICATION)
will be converted to "WINDOWSAUTHENTICATION"
at compile time, making it the quickest way to get enum names.
Note that this will convert the explicit enum to an inlined constant, so it doesn't work for enums that you have in a variable. So:
nameof(AuthenticationMethod.FORMS) == "FORMS"
But...
var myMethod = AuthenticationMethod.FORMS;
nameof(myMethod) == "myMethod"