Internally the enumeration value is assigned as integer, but ToString method to display an enumeration value in textual or numeric value. The method can accept a character to indicate the type of formatting to place on the enumeration value. The table below shows the available type of formatting.

Type of Formatting Description
G or g (General) Displays the string representation of the enumeration value.
F or f (Flag) Displays the string representation of the enumeration value. The enumeration is treated as if it were a bit field.
D or d (Decimal) Displays decimal equivalent of the enumeration.
X or x (Hexadecimal) Displays hexadecimal equivalent of the enumeration.

By using the example RiskLevel as following:

enum RiskLevel
{
    Lowest = 0, Low = 1, Medium = 2, High = 4, Highest = 8
}

Using the ToString method of the RiskLevel enumeration type, we can derive the value of a specific RiskLevel enumeration value directly:

Console.WriteLine(RiskLevel.Low.ToString());
Console.WriteLine(RiskLevel.Low.ToString("G"));
Console.WriteLine(RiskLevel.Low.ToString("D"));
Console.WriteLine(RiskLevel.Low.ToString("F"));
Console.WriteLine(RiskLevel.Low.ToString("X"));

This generates the following output:

Low
Low
1
Low
00000001

Or it work in the same manner on a variable of type RiskLevel

RiskLevel riskLevel = RiskLevel.Highest;

When printing out the values of an enumeration with the Flags attribute, the information displayed takes into account that more than one of the enumeration values may have been ORed together. The output will be all of the enumerations printed out as strings separated by commas or as the ORed numeric value, depending on the formatting chosen. For example, consider if the Flags attribute were added to the RiskLevel enumeration as follows:

[Flags]
enum RiskLevel
{
    Lowest = 0, Low = 1, Medium = 2, High = 4, Highest = 8
}

and if we changed the code as below:

RiskLevel riskLevel = RiskLevel.Low | RiskLevel.Medium;

Console.WriteLine(riskLevel.ToString( ));
Console.WriteLine(riskLevel.ToString("G"));
Console.WriteLine(riskLevel.ToString("D"));
Console.WriteLine(riskLevel.ToString("F"));
Console.WriteLine(riskLevel.ToString("X"));

you would see the following output:

Low, Medium
Low, Medium
3
Low, Medium
00000003

This technique provides a flexible way of extracting the flags that we are currently using on an enumeration type.

Popularity: 100% [?]