I don't know what the "preferred" method is (ask 100 people and get 100 different opinions) but do what's simplest and what works. GetName
works but requires a lot more keystrokes. ToString()
seems to do the job very well.
In my tests, Enum.GetName
was faster and by decent margin. Internally ToString
calls Enum.GetName
. From source for .NET 4.0, the essentials:
public override String ToString()
{
return Enum.InternalFormat((RuntimeType)GetType(), GetValue());
}
private static String InternalFormat(RuntimeType eT, Object value)
{
if (!eT.IsDefined(typeof(System.FlagsAttribute), false))
{
String retval = GetName(eT, value); //<== the one
if (retval == null)
return value.ToString();
else
return retval;
}
else
{
return InternalFlagsFormat(eT, value);
}
}
I cant say that is the reason for sure, but tests state one is faster than the other. Both the calls involve boxing (in fact they are reflection calls, you're essentially retrieving field names) and can be slow for your liking.
Test setup: enum with 8 values, no. of iterations = 1000000
Result: Enum.GetName => 700 ms, ToString => 2000 ms
If speed isn't noticeable, I wouldn't care and use ToString
since it offers a much cleaner call. Contrast
Enum.GetName(typeof(Bla), value)
with
value.ToString()
For VB aficionados:
EnumStringValue = System.Enum.GetName(GetType(MyEnum), MyEnumValue)
Works for our project...
public static String convertToString(this Enum eff)
{
return Enum.GetName(eff.GetType(), eff);
}
public static EnumType converToEnum<EnumType>(this String enumValue)
{
return (EnumType) Enum.Parse(typeof(EnumType), enumValue);
}
I create a "Description" extension method and attach it to the enum so that i can get truly user-friendly naming that includes spaces and casing. I have never liked using the enum value itself as displayable text because it is something we developers use to create more readable code. It is not intended for UI display purposes. I want to be able to change the UI without going through and changing enums all over.
This is the most elegant method that is meant for it.
var enumValueString = Enum.GetName(typeof (MyEnum), MyEnum.MyValue);
Although I don't see any issues with calling .ToString()
as it is simply shorter.
var enumValueString = MyEnum.MyValue.ToString();
With new C# 6 syntax you can use:
nameof(MyEnum.MyValue)
ToString()
gives the most obvious result from a readability perspective, while using Enum.GetName()
requires a bit more mental parsing to quickly understand what its trying to do (unless you see the pattern all the time).
From a pure performance point of view, as already provided in @nawfal's answer, Enum.GetName()
is better.
If performance is really your goal though, it would be even better to provide a look-up beforehand (using a Dictionary or some other mapping).
In C++/CLI, this would look like
Dictionary<String^, MyEnum> mapping;
for each (MyEnum field in Enum::GetValues(MyEnum::typeid))
{
mapping.Add(Enum::GetName(MyEnum::typeid), field);
}
Comparison using an enum of 100 items and 1000000 iterations:
Enum.GetName: ~800ms
.ToString(): ~1600ms
Dictionary mapping: ~250ms
Best I can find is this unrelated question on MSDN, which contains an XML snippet that answers this question. Any of these methods share the same flaw: they call enum.toString()
, which does not work properly when using Dotfuscation. Other concerns appear to relate to indirect boxing (GetName and Format). Unfortunately, I can't find any performance reasons for using any of the above.
Paraphrasing from the xml snippet,
Passing a boxed enum to string.Format() or any other function can result in
enum.ToString()
being called. This will cause problems when Dotfuscating. You should not useenum.ToString()
,enum.GetNames()
,enum.GetName()
,enum.Format()
orenum.Parse()
to convert an enum to a string. Instead, use a switch statement, and also internationalize the names if necessary.
In my tests, Enum.GetName
was faster and by decent margin. Internally ToString
calls Enum.GetName
. From source for .NET 4.0, the essentials:
public override String ToString()
{
return Enum.InternalFormat((RuntimeType)GetType(), GetValue());
}
private static String InternalFormat(RuntimeType eT, Object value)
{
if (!eT.IsDefined(typeof(System.FlagsAttribute), false))
{
String retval = GetName(eT, value); //<== the one
if (retval == null)
return value.ToString();
else
return retval;
}
else
{
return InternalFlagsFormat(eT, value);
}
}
I cant say that is the reason for sure, but tests state one is faster than the other. Both the calls involve boxing (in fact they are reflection calls, you're essentially retrieving field names) and can be slow for your liking.
Test setup: enum with 8 values, no. of iterations = 1000000
Result: Enum.GetName => 700 ms, ToString => 2000 ms
If speed isn't noticeable, I wouldn't care and use ToString
since it offers a much cleaner call. Contrast
Enum.GetName(typeof(Bla), value)
with
value.ToString()
I create a "Description" extension method and attach it to the enum so that i can get truly user-friendly naming that includes spaces and casing. I have never liked using the enum value itself as displayable text because it is something we developers use to create more readable code. It is not intended for UI display purposes. I want to be able to change the UI without going through and changing enums all over.
Best I can find is this unrelated question on MSDN, which contains an XML snippet that answers this question. Any of these methods share the same flaw: they call enum.toString()
, which does not work properly when using Dotfuscation. Other concerns appear to relate to indirect boxing (GetName and Format). Unfortunately, I can't find any performance reasons for using any of the above.
Paraphrasing from the xml snippet,
Passing a boxed enum to string.Format() or any other function can result in
enum.ToString()
being called. This will cause problems when Dotfuscating. You should not useenum.ToString()
,enum.GetNames()
,enum.GetName()
,enum.Format()
orenum.Parse()
to convert an enum to a string. Instead, use a switch statement, and also internationalize the names if necessary.
Works for our project...
public static String convertToString(this Enum eff)
{
return Enum.GetName(eff.GetType(), eff);
}
public static EnumType converToEnum<EnumType>(this String enumValue)
{
return (EnumType) Enum.Parse(typeof(EnumType), enumValue);
}
Enum.GetName()
Format()
is really just a wrapper around GetName()
with some formatting functionality (or InternalGetValueAsString()
to be exact). ToString()
is pretty much the same as Format()
. I think GetName()
is best option since it's totally obvious what it does for anyone who reads the source.
I don't know what the "preferred" method is (ask 100 people and get 100 different opinions) but do what's simplest and what works. GetName
works but requires a lot more keystrokes. ToString()
seems to do the job very well.
Enum.GetName()
Format()
is really just a wrapper around GetName()
with some formatting functionality (or InternalGetValueAsString()
to be exact). ToString()
is pretty much the same as Format()
. I think GetName()
is best option since it's totally obvious what it does for anyone who reads the source.
ToString()
gives the most obvious result from a readability perspective, while using Enum.GetName()
requires a bit more mental parsing to quickly understand what its trying to do (unless you see the pattern all the time).
From a pure performance point of view, as already provided in @nawfal's answer, Enum.GetName()
is better.
If performance is really your goal though, it would be even better to provide a look-up beforehand (using a Dictionary or some other mapping).
In C++/CLI, this would look like
Dictionary<String^, MyEnum> mapping;
for each (MyEnum field in Enum::GetValues(MyEnum::typeid))
{
mapping.Add(Enum::GetName(MyEnum::typeid), field);
}
Comparison using an enum of 100 items and 1000000 iterations:
Enum.GetName: ~800ms
.ToString(): ~1600ms
Dictionary mapping: ~250ms
Simple: enum names into a List:
List<String> NameList = Enum.GetNames(typeof(YourEnumName)).Cast<string>().ToList()
For VB aficionados:
EnumStringValue = System.Enum.GetName(GetType(MyEnum), MyEnumValue)
Enum.GetName()
Format()
is really just a wrapper around GetName()
with some formatting functionality (or InternalGetValueAsString()
to be exact). ToString()
is pretty much the same as Format()
. I think GetName()
is best option since it's totally obvious what it does for anyone who reads the source.
Best I can find is this unrelated question on MSDN, which contains an XML snippet that answers this question. Any of these methods share the same flaw: they call enum.toString()
, which does not work properly when using Dotfuscation. Other concerns appear to relate to indirect boxing (GetName and Format). Unfortunately, I can't find any performance reasons for using any of the above.
Paraphrasing from the xml snippet,
Passing a boxed enum to string.Format() or any other function can result in
enum.ToString()
being called. This will cause problems when Dotfuscating. You should not useenum.ToString()
,enum.GetNames()
,enum.GetName()
,enum.Format()
orenum.Parse()
to convert an enum to a string. Instead, use a switch statement, and also internationalize the names if necessary.
I create a "Description" extension method and attach it to the enum so that i can get truly user-friendly naming that includes spaces and casing. I have never liked using the enum value itself as displayable text because it is something we developers use to create more readable code. It is not intended for UI display purposes. I want to be able to change the UI without going through and changing enums all over.
All of these internally end up calling a method called InternalGetValueAsString
. The difference between ToString
and GetName
would be that GetName
has to verify a few things first:
GetType
on the value to check this. .ToString
doesn't have to worry about any of these above issues, because it is called on an instance of the class itself, and not on a passed in version, therefore, due to the fact that the .ToString
method doesn't have the same verification issues as the static methods, I would conclude that .ToString
is the fastest way to get the value as a string.
I don't know what the "preferred" method is (ask 100 people and get 100 different opinions) but do what's simplest and what works. GetName
works but requires a lot more keystrokes. ToString()
seems to do the job very well.
Enum.GetName()
Format()
is really just a wrapper around GetName()
with some formatting functionality (or InternalGetValueAsString()
to be exact). ToString()
is pretty much the same as Format()
. I think GetName()
is best option since it's totally obvious what it does for anyone who reads the source.
This is the most elegant method that is meant for it.
var enumValueString = Enum.GetName(typeof (MyEnum), MyEnum.MyValue);
Although I don't see any issues with calling .ToString()
as it is simply shorter.
var enumValueString = MyEnum.MyValue.ToString();
With new C# 6 syntax you can use:
nameof(MyEnum.MyValue)
Simple: enum names into a List:
List<String> NameList = Enum.GetNames(typeof(YourEnumName)).Cast<string>().ToList()
All of these internally end up calling a method called InternalGetValueAsString
. The difference between ToString
and GetName
would be that GetName
has to verify a few things first:
GetType
on the value to check this. .ToString
doesn't have to worry about any of these above issues, because it is called on an instance of the class itself, and not on a passed in version, therefore, due to the fact that the .ToString
method doesn't have the same verification issues as the static methods, I would conclude that .ToString
is the fastest way to get the value as a string.
This would work too.
List<string> names = Enum.GetNames(typeof(MyEnum)).ToList();
Best I can find is this unrelated question on MSDN, which contains an XML snippet that answers this question. Any of these methods share the same flaw: they call enum.toString()
, which does not work properly when using Dotfuscation. Other concerns appear to relate to indirect boxing (GetName and Format). Unfortunately, I can't find any performance reasons for using any of the above.
Paraphrasing from the xml snippet,
Passing a boxed enum to string.Format() or any other function can result in
enum.ToString()
being called. This will cause problems when Dotfuscating. You should not useenum.ToString()
,enum.GetNames()
,enum.GetName()
,enum.Format()
orenum.Parse()
to convert an enum to a string. Instead, use a switch statement, and also internationalize the names if necessary.
All of these internally end up calling a method called InternalGetValueAsString
. The difference between ToString
and GetName
would be that GetName
has to verify a few things first:
GetType
on the value to check this. .ToString
doesn't have to worry about any of these above issues, because it is called on an instance of the class itself, and not on a passed in version, therefore, due to the fact that the .ToString
method doesn't have the same verification issues as the static methods, I would conclude that .ToString
is the fastest way to get the value as a string.
This would work too.
List<string> names = Enum.GetNames(typeof(MyEnum)).ToList();
Source: Stackoverflow.com