Enum.Format
This C# method changes enums to strings. It produces hexadecimal, digit and string
values from an enumerated constant.
string
infoThe Enum.Format
method uses format strings for this. Lowercase and uppercase make no difference. A single-char
string
argument can be passed to Enum.Format
.
To begin, this program uses all 8 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.
string
.enum
in hexadecimal or digit format.typeof
operator can be passed as the second argument to 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); } }G = Critical g = Critical X = 00000002 x = 00000002 F = Critical f = Critical D = 2 d = 2
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.
ToString
, but Format is another alternative.Enum.Format
method is not needed but could provide a useful bit of functionality for some programs.Enum.Format
produces a string
representation in a standardized format from an enumerated constant. It provides an alternative to the ToString
method and casting.