C# Enum.Format Method (typeof Enum)

Use the Enum.Format method with the typeof operator to get strings from enums.
Enum.Format. This changes enums to strings. It produces hexadecimal, digit and string values from an enumerated constant. It uses format strings for this. Lowercase and uppercase make no difference.Enum
To begin, let us look at a program that uses all eight different formatting strings accepted by Enum.Format. We use a sample enum to demonstrate as well. The output shows the exact results of these formats.
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.

Typeof: The typeof operator can be passed as the second argument to Enum.Format.

Typeof, nameof
C# program that demonstrates Enum.Format 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
Usage notes. 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.

Tip: You could do this by casting to the underlying type and then using ToString, but Format is another alternative.

Summary. 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 method is not needed but could provide a useful bit of functionality for some programs.

© 2007-2020 Sam Allen. Every person is special and unique. Send bug reports to
Dot Net Perls