Mono Class Library: System.Enum Overview | Members

System.Enum.Format Method

Converts the specified element of the specified enumeration type to its string representation using the specified format. [Edit]

[System.Runtime.InteropServices.ComVisible(true)]
public static string Format (Type enumType, object value, string format)

Parameters

enumType
A Type that specifies the type of the enumeration of which value is a member. [Edit]
value
The enumeration element to be converted. [Edit]
format
A string that specifies the output format to use. [Edit]
value
Documentation for this section has not yet been entered. [Edit]
format
Documentation for this section has not yet been entered. [Edit]

Returns

The string representation of the value of the enumeration element. [Edit]

Exceptions

TypeReason
ArgumentNullExceptionenumType, value or format is a null reference. [Edit]
ArgumentException

enumType is not a Enum.

-or-

value is neither of type enumType nor does it have the same underlying type as enumType.

[Edit]
FormatExceptionformat contains an invalid value. [Edit]

Remarks

For cross-platform portability, the only valid values for format are:

Format Description
"G" or "g"

If value is equal to a defined value of enumType , returns the element name defined for value. If the FlagsAttribute attribute is set on the Enum declaration and value is a built-in integer type and is equal to a summation of enumeration elements, the return value contains the element names in an unspecified order, separated by commas (e.g. "Red, Yellow"). Otherwise, value is returned in decimal format.

"X" or "x" Returns value in hexadecimal format, without a leading 0x. The value is padded with leading zeroes to ensure the returned value is at least eight digits in length.
"F" or "f"Behaves identically to "G", except the FlagsAttribute is not required to be present on the Enum declaration.
"D" or "d" Returns value in decimal format with no leading zeroes.
[Edit]

Example

The following example demonstrates formatting enumeration values.

C# Example
using System;
public enum Signs {
  Stop = 1,
  Yield = 2,
  Merge = 4
};
[Flags]
public enum Lights {
  Red = 1,
  Yellow = 2,
  Green = 4
};
public class EnumCompTo {
  public static void Main() {
   Console.WriteLine(Signs.Format(typeof(Signs), Signs.Merge, "d"));
   Console.WriteLine(Signs.Format(typeof(Signs), 7, "g"));
   Console.WriteLine(Lights.Format(typeof(Lights), Lights.Yellow, "x"));
   Console.WriteLine(Lights.Format(typeof(Lights), 7, "g"));
  }
}
   

The output is

4
7
00000002
Red, Yellow, Green

Requirements

Namespace: System
Assembly: mscorlib (in mscorlib.dll)
Assembly Versions: 1.0.5000.0, 2.0.0.0