Enum.ToString
This C# method converts an enum
into a string
. This string
can be used to display the name of the enum
with Console.WriteLine
.
Result
valueThe result string
from Enum.ToString
can be stored in a string
variable or field. We can format and print the result.
To declare an enum
type we use the enum
keyword. The enumerated constants can be any identifier, and their actual values are automatically incremented.
Priority.None
enum
will have value of 0. And the Priority.Critical
enum
will have value of 4.ToString
virtual
method will look into the assembly metadata to get the string
value to return.enum
should be a "None
" or "Zero" value so it can be correctly tested against zero.string
values in the enum
. The GetNames
method returns the same strings.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); } } }::FOR:: None Trivial Normal Important Critical ::GETVALUES:: None Trivial Normal Important Critical
The base.GetType()
call, the GetValueField
call, and InternalGetValue
use reflection. They acquire the string
representation from the enum
constant from your source metadata.
public override string ToString() { Type type = base.GetType(); object obj2 = ((RtFieldInfo)GetValueField(type)) .InternalGetValue(this, false); return InternalFormat(type, obj2); }
There is a static
Enum.GetNames
method that receives one Type parameter in the Enum
class
. This method provides a clearer way to get an array of all of the enum
strings.
GetNames
method instead of the for
-loop construct as shown. There are drawbacks to both approaches.ToString
uses reflection. It returns an enum
's string
representation. We saw an example of the output of calling ToString
on all values in an enumerated type.