TheDeveloperBlog.com


C# Enum ToString Method

Enum.ToString 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. It can be passed to any method that requires a string.


Example. First, to declare an enum type in the C# language you must 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, while 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.

Virtual
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 enum1 = Priority.Important;
	string value1 = enum1.ToString();

	// Loop through enumerations.
	// Write string representations. (See GetNames)
	for (Priority enum2 = Priority.None;
	    enum2 <= Priority.Critical;
	    enum2++)
	{
	    string value2 = enum2.ToString();
	    Console.WriteLine(value2);
	}
    }
}

Output

None
Trivial
Normal
Important
Critical

The program contains an enum called Priority. This contains five different enumerated constants. The first enumerated constant in the enum should usually be a "None" or "Zero" value so it can be correctly tested against zero.

Then: We print the five string values in the enum. The GetNames method would return the same strings.


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

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


Discussion. There is a public static Enum.GetNames method that receives one Type parameter in the Enum class in the C# language. This method provides a clearer way to get an array of all of the strings represented in the enumerated type.

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

Enum.GetName

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, and looked inside the Enum class ToString method.