format item of C# String.Format

The format item
A format item has this syntax:

{index[ ,alignment][ :formatString] }
Brackets denote optional elements. The opening and closing braces are required. (To include a literal opening or closing brace in the format string, see the “Escaping Braces” section in the Composite Formatting article.)

For example, a format item to format a currency value might appears like this:

String.Format(“{0,-10:C}”, 126347.89m);
String.Format(“{0,-10:C}”, 126347.89m);
String::Format(“{0,-10:C}”, (Decimal) 126347.89);
String::Format(“{0,-10:C}”, (Decimal) 126347.89);
String.Format(“{0,-10:C}”, 126347.89d)
String.Format(“{0,-10:C}”, 126347.89d)

A format item has the following elements:

The zero-based index of the argument whose string representation is to be included at this position in the string. If this argument is null, an empty string will be included at this position in the string.

Optional. A signed integer that indicates the total length of the field into which the argument is inserted and whether it is right-aligned (a positive integer) or left-aligned (a negative integer). If you omit alignment, the string representation of the corresponding argument is inserted in a field with no leading or trailing spaces.

Optional. A string that specifies the format of the corresponding argument’s result string. If you omit formatString, the corresponding argument’s parameterless ToString method is called to produce its string representation. If you specify formatString, the argument referenced by the format item must implement the IFormattable interface. Types that support format strings include:

All integral and floating-point types. (See Standard Numeric Format Strings and Custom Numeric Format Strings.)

DateTime and DateTimeOffset. (See Standard Date and Time Format Strings and Custom Date and Time Format Strings.)

All enumeration types. (See Enumeration Format Strings.)

TimeSpan values. (See Standard TimeSpan Format Strings and Custom TimeSpan Format Strings.)

GUIDs. (See the Guid.ToString(String) method.)

However, note that any custom type can implement IFormattable or extend an existing type’s IFormattable implementation.

Leave a Reply

Your email address will not be published. Required fields are marked *