Home
Map
Enum.Format MethodUse the Enum.Format method with the typeof operator to get strings from enums.
C#
This page was last reviewed on Dec 4, 2021.
Enum.Format. This C# method changes enums to strings. It produces hexadecimal, digit and string values from an enumerated constant.
Format string info. The 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.
enum
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.
Info The constants "G", "g", "F", and "f" all output the name of the enumerated constant as a string.
String Literal
Detail The constants "X", "x", "D", and "d" output the value of the enum in hexadecimal or digit format.
Detail The typeof operator can be passed as the second argument to Enum.Format.
typeof, nameof
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
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.
ToString
Detail The Enum.Format method is not needed but could provide a useful bit of functionality for some programs.
Summary. Enum.Format produces a string representation in a standardized format from an enumerated constant. It provides an alternative to the ToString method and casting.
Dot Net Perls is a collection of tested code examples. Pages are continually updated to stay current, with code correctness a top priority.
Sam Allen is passionate about computer languages. In the past, his work has been recommended by Apple and Microsoft and he has studied computers at a selective university in the United States.
This page was last updated on Dec 4, 2021 (rewrite).
Home
Changes
© 2007-2024 Sam Allen.