Export (0) Print
Expand All

Composite Formatting

The .NET Framework composite formatting feature enables you to provide a list of values and a source string consisting of alternating fixed text and indexed placeholders, and easily obtain a result string consisting of the original fixed text intermixed with formatted values. Use composite formatting with methods such as String.Format, which returns a formatted string, Console.WriteLine, which displays the result string to the console, or an implementation of TextWriter.WriteLine, which writes the result string to a stream or file.

Each indexed placeholder, or format item, corresponds to one element in a list of values. The composite formatting feature returns a new result string where each format item embedded in the source string is replaced by the corresponding formatted value.

The source string consists of zero or more runs of fixed text interrupted by one or more format items. The fixed text can contain any content you choose.

Consider the following String.Format example.

Dim myName As String = "Fred"
String.Format("Name = {0}, hours = {1:hh}", myName, DateTime.Now)
[C#]
string myName = "Fred";
String.Format("Name = {0}, hours = {1:hh}", myName, DateTime.Now);

The fixed text is "Name = " and ", hours = ", the format items are "{0}" and "{1:hh}", and the list of values is myName and DateTime.Now.

Format Item Syntax

Each format item takes the following form.

{index[,alignment][:formatString]}

The matching braces ("{" and "}") are required. Because opening and closing braces are interpreted as starting and ending a format item, you must specify two opening braces ("{{") in the fixed text to display one opening brace ("{"), and specify two closing braces ("}}") in the fixed text to display one closing brace ("}").

A format item consists of the following components.

Index Component

The mandatory index component, also called a parameter specifier, is a number starting from 0 that identifies a corresponding element in the list of values. That is, the format item whose parameter specifier is 0 formats the first value in the list, the format item whose parameter specifier is 1 formats the second value in the list, and so on.

Multiple format items can refer to the same element in the list of values by specifying the same parameter specifier. For example, you can format the same numeric value in hexadecimal, scientific, and number format by specifying a source string like this: "{0:X} {0:E} {0:N}".

Each format item can refer to any parameter. For example, if there are three values, you can format the second, first, and third value by specifying a source string like this: "{1} {0} {2}". A value that is not referenced by a format item is ignored. A runtime exception results if a parameter specifier designates an item outside the bounds of the list of values.

Alignment Component

The optional alignment component is a signed integer indicating the preferred formatted field width. If the value of alignment is less than the length of the formatted string, alignment is ignored and the length of the formatted string is used as the field width. The formatted data in the field is right-aligned if alignment is positive, and left-aligned if alignment is negative. If padding is necessary, white space is used. The comma is required if alignment is specified.

Format String Component

The optional formatString component consists of standard or custom format specifiers. If formatString is not specified, the general ("G") format specifier is used. The colon is required if formatString is specified.

Processing Order

If the value to be formatted is null (Nothing in Visual Basic), an empty string ("") is returned.

If the type to be formatted implements the ICustomFormatter interface, the ICustomFormatter.Format method is called.

If the preceding step does not format the type, and the type implements the IFormattable interface, the IFormattable.ToString method is called.

If the preceding step does not format the type, the type's ToString method, which is inherited from the Object class, is called.

Alignment is applied after the preceding steps have been performed.

Code Examples

The following example shows one string created using composite formatting and another created using an object's ToString method. Both types of formatting produce equivalent results.

Dim FormatString1 As String = String.Format("{0:dddd MMMM}", DateTime.Now)
Dim FormatString2 As String = DateTime.Now.ToString("dddd MMMM") 
[C#]
string FormatString1 = String.Format("{0:dddd MMMM}", DateTime.Now);
string FormatString2 = DateTime.Now.ToString("dddd MMMM");

Assuming that the current day is a Thursday in May, the value of both strings in the preceding example is Thursday May in the U.S. English culture.

Console.WriteLine exposes the same functionality as String.Format. The only difference between the two methods is that String.Format returns its result as a string, while Console.WriteLine writes the result to the output stream associated with the Console object. The following example uses the Console.WriteLine method to format the value of MyInt to a currency value.

Dim MyInt As Integer = 100
Console.WriteLine("{0:C}", MyInt)
[C#]
int MyInt = 100;
Console.WriteLine("{0:C}", MyInt);

This code displays $100.00 to the console on computers that have U.S. English as the current culture.

The following example demonstrates formatting multiple objects, including formatting one object two different ways.

Dim myName As String = "Fred"
String.Format("Name = {0}, hours = {1:hh}, minutes = {1:mm}",
      myName, DateTime.Now)
[C#]
string myName = "Fred";
String.Format("Name = {0}, hours = {1:hh}, minutes = {1:mm}",
      myName, DateTime.Now);

The output from the preceding string is "Name = Fred, hours = 07, minutes = 23", where the current time reflects these numbers.

The following examples demonstrate the use of alignment in formatting. The arguments that are formatted are placed between vertical bar characters (|) to highlight the resulting alignment.

Dim myFName As String = "Fred"
Dim myLName As String = "Opals"
Dim myInt As Integer = 100
Dim FormatFName As String = String.Format("First Name = |{0,10}|", myFName)
Dim FormatLName As String = String.Format("Last Name = |{0,10}|", myLName)
Dim FormatPrice As String = String.Format("Price = |{0,10:C }|", myInt)
Console.WriteLine(FormatFName)
Console.WriteLine(FormatLName)
Console.WriteLine(FormatPrice)

FormatFName = String.Format("First Name = |{0,-10}|", myFName)
FormatLName = String.Format("Last Name = |{0,-10}|", myLName)
FormatPrice = String.Format("Price = |{0,-10:C }|", myInt)
Console.WriteLine(FormatFName)
Console.WriteLine(FormatLName)
Console.WriteLine(FormatPrice)
[C#]
string myFName = "Fred";
string myLName = "Opals";
int myInt = 100;
string FormatFName = String.Format("First Name = {0,10}", myFName);
string FormatLName = String.Format("Last Name = {0,10}", myLName);
string FormatPrice = String.Format("Price = {0,10:C}", myInt); 
Console.WriteLine(FormatFName);
Console.WriteLine(FormatLName);
Console.WriteLine(FormatPrice);

FormatFName = String.Format("First Name = |{0,-10}|", myFName);
FormatLName = String.Format("Last Name = |{0,-10}|", myLName);
FormatPrice = String.Format("Price = |{0,-10:C}|", myInt);
Console.WriteLine(FormatFName);
Console.WriteLine(FormatLName);
Console.WriteLine(FormatPrice);

The preceding code displays the following to the console in the U.S. English culture. Different cultures display different currency symbols and separators.

First Name = |          Fred|
Last Name = |         Opals|
Price = |           $100.00|
First Name = |Fred      |
Last Name = |Opals     |
Price = |$100.00   |

See Also

Formatting Types | Formatting Overview | Console.Writeline | String.Format | System.IO

Show:
© 2014 Microsoft