C# Enum ToString: Convert Enum to String

This C# example converts an enum into a string with the ToString method. The ToString implementation is inspected.


This converts an enum into a string. This string can be used to display the name of the enum. It can be stored in a string variable or field.

An example.

To declare an enum type we use the enum keyword. The enumerated constants can be any identifier, and their actual values are automatically incremented.

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.

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

Above program, notes.

We see an enum called Priority. The first enumerated constant in the enum should be a "None" or "Zero" value so it can be correctly tested against zero.

Then: We print the 5 string values in the enum. The GetNames method returns the same strings.


The base.GetType() call, the GetValueField call, and InternalGetValue use reflection. They acquire the string representation from the enum constant from your source metadata.

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); }

A discussion.

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.

Often: It is preferable to use the GetNames method instead of the for-loop construct as shown. There are drawbacks to both approaches.


Credit: Thanks to Mike for pointing out the importance of using GetValues for clear C# code.

A summary.

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.Enum
Dot Net Perls
© 2007-2019 Sam Allen. All rights reserved. Written by Sam Allen,