C# Enum.Format

Format illustration

Enum.Format is a standardized way to change enums to strings. It produces hexadecimal, digit and string values from an enumerated constant. It uses format strings such as "x" for this. Lowercase and uppercase make no difference.

Example

Note

To begin, let's look at a program text that uses all eight different formatting strings accepted by Enum.Format. We use a sample enum to demonstrate as well. The constants G, g, F, and f all output the name of the enumerated constant as a string. The constants X, x, D, and d output the value of the enum in hexadecimal or digit format, respectively.

This C# example program uses the Enum.Format method. It uses the typeof operator.

Program that demonstrates Enum.Format [C#]

using System;

class Program
{
    enum Importance
    {
	Low,
	Medium,
	Critical
    }

    static void Main()
    {
	M("G");
	M("g");
	M("X");
	M("x");
	M("F");
	M("f");
	M("D");
	M("d");
    }

    static void M(string format)
    {
	// Use Enum.Format with the specified format string.
	string value = Enum.Format(typeof(Importance), Importance.Critical, format);
	Console.WriteLine("{0} = {1}", format, value);
    }
}

Output

G = Critical
g = Critical
X = 00000002
x = 00000002
F = Critical
f = Critical
D = 2
d = 2
Question and answer

Uses for the method. So what is the use of the Enum.Format method in a real program? It provides a standardized way to produce a string that represents either the name or the value of an enum type. You could do this by casting to the underlying type and then using ToString, but this is another alternative.

Summary

The C# programming language

In this article, the Enum.Format method was used to produce a string representation in a standardized format from an enumerated constant. The method provides an alternative to the ToString method and casting. Typically the Enum.Format is not needed but could provide a useful bit of functionality for some programs.

Enum Examples
.NET