C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
Next: In this program, the Priority.None enum will have value of 0. And the Priority.Critical enum will have value of 4.
Note: The ToString virtual method will look into the assembly metadata to get the string value to return.
VirtualTip: The first enumerated constant in an enum should be a "None" or "Zero" value so it can be correctly tested against zero.
Finally: We print the 5 string values in the enum. The GetNames method returns the same strings.
C# program that converts enumeration to string
using System;
enum Priority
{
None,
Trivial,
Normal,
Important,
Critical
}
class Program
{
static void Main()
{
// Write string representation for Important.
Priority priorityValue = Priority.Important;
string enumValue = priorityValue.ToString();
// Loop through enumerations.
// ... Write string representations.
Console.WriteLine("::FOR::");
for (Priority p = Priority.None;
p <= Priority.Critical;
p++)
{
string value = p.ToString();
Console.WriteLine(value);
}
Console.WriteLine("::GETVALUES::");
foreach (Priority p in Enum.GetValues(typeof(Priority)))
{
string value = p.ToString();
Console.WriteLine(value);
}
}
}
Output
::FOR::
None
Trivial
Normal
Important
Critical
::GETVALUES::
None
Trivial
Normal
Important
Critical
Warning: This has a performance impact. But it also reduces the complexity the source code. You do not need to store the strings yourself.
Implementation of enumeration ToString
public override string ToString()
{
Type type = base.GetType();
object obj2 = ((RtFieldInfo)GetValueField(type))
.InternalGetValue(this, false);
return InternalFormat(type, obj2);
}
Often: It is preferable to use the GetNames method instead of the for-loop construct as shown. There are drawbacks to both approaches.
Enum.GetNameCredit: Thanks to Mike for pointing out the importance of using GetValues for clear C# code.