String.Format Method (System)

Switch View :
ScriptFree
.NET Framework Class Library
String.Format Method

Updated: September 2011

Replaces each format item in a specified string with the text equivalent of a corresponding object's value.

This member is overloaded. For complete information about this member, including syntax, usage, and examples, click a name in the overload list.

Overload List

  Name Description
Public method Static member Format(String, Object) Replaces one or more format items in a specified string with the string representation of a specified object.
Public method Static member Format(String, Object[]) Replaces the format item in a specified string with the string representation of a corresponding object in a specified array.
Public method Static member Format(IFormatProvider, String, Object[]) Replaces the format item in a specified string with the string representation of a corresponding object in a specified array. A specified parameter supplies culture-specific formatting information.
Public method Static member Format(String, Object, Object) Replaces the format items in a specified string with the string representation of two specified objects.
Public method Static member Format(String, Object, Object, Object) Replaces the format items in a specified string with the string representation of three specified objects.
Top
Remarks

Each overload of the Format method uses the composite formatting feature to include zero-based indexed placeholders, called format items, in a composite format string. At run time, each format item is replaced with the string representation of the corresponding argument in a parameter list. If the value of the argument is null, it is replaced with String.Empty. For example, the following call to the Format method includes a format string with three format items, {0}, {1}, and {2}, and an argument list with three items.

Visual Basic

Dim dat As Date = #1/17/2012 9:30AM# 
Dim city As String = "Chicago"
Dim temp As Integer = -16
Dim output As String = String.Format("At {0} in {1}, the temperature was {2} degrees.",
                                     dat, city, temp)
Console.WriteLine(output)
' The example displays the following output:
'    At 1/17/2012 9:30:00 AM in Chicago, the temperature was -16 degrees.   


C#

DateTime dat = new DateTime(2012, 1, 17, 9, 30, 0); 
string city = "Chicago";
int temp = -16;
string output = String.Format("At {0} in {1}, the temperature was {2} degrees.",
                              dat, city, temp);
Console.WriteLine(output);
// The example displays the following output:
//    At 1/17/2012 9:30:00 AM in Chicago, the temperature was -16 degrees.   


A format item has the following syntax:

{ index[,alignment][ : formatString] }

Brackets denote optional elements. The opening and closing brackets are required. A format item has the following elements:

index

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

alignment

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 alignment is omitted, the string representation of the corresponding argument is inserted in a field with no leading or trailing spaces.

formatString

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

The following example illustrates how to use optional elements in format items to produce formatted output.

Visual Basic

Module Example
   Public Sub Main()
      ' Create array of 5-tuples with population data for three U.S. cities, 1940-1950.
      Dim cities()  = _
          { Tuple.Create("Los Angeles", #1/1/1940#, 1504277, #1/1/1950#, 1970358),
            Tuple.Create("New York", #1/1/1940#, 7454995, #1/1/1950#, 7891957),  
            Tuple.Create("Chicago", #1/1/1940#, 3396808, #1/1/1950#, 3620962),  
            Tuple.Create("Detroit", #1/1/1940#, 1623452, #1/1/1950#, 1849568) }

      ' Display header
      Dim header As String = String.Format("{0,-12}{1,8}{2,12}{1,8}{2,12}{3,14}",
                                           "City", "Year", "Population", "Change (%)")
      Console.WriteLine(header)
      Console.WriteLine()
      Dim output As String      
      For Each city In cities
         output = String.Format("{0,-12}{1,8:yyyy}{2,12:N0}{3,8:yyyy}{4,12:N0}{5,14:P1}",
                                city.Item1, city.Item2, city.Item3, city.Item4, city.Item5,
                                (city.Item5 - city.Item3)/city.Item3)
         Console.WriteLine(output)
      Next
   End Sub
End Module
' The example displays the following output:
'    City            Year  Population    Year  Population    Change (%)
'    
'    Los Angeles     1940   1,504,277    1950   1,970,358        31.0 %
'    New York        1940   7,454,995    1950   7,891,957         5.9 %
'    Chicago         1940   3,396,808    1950   3,620,962         6.6 %
'    Detroit         1940   1,623,452    1950   1,849,568        13.9 %


C#

using System;

public class Example
{
   public static void Main()
   {
      // Create array of 5-tuples with population data for three U.S. cities, 1940-1950.
      Tuple<string, DateTime, int, DateTime, int>[] cities = 
          { Tuple.Create("Los Angeles", new DateTime(1940, 1, 1), 1504277, 
                         new DateTime(1950, 1, 1), 1970358),
            Tuple.Create("New York", new DateTime(1940, 1, 1), 7454995, 
                         new DateTime(1950, 1, 1), 7891957),  
            Tuple.Create("Chicago", new DateTime(1940, 1, 1), 3396808, 
                         new DateTime(1950, 1, 1), 3620962),  
            Tuple.Create("Detroit", new DateTime(1940, 1, 1), 1623452, 
                         new DateTime(1950, 1, 1), 1849568) };

      // Display header
      string header = String.Format("{0,-12}{1,8}{2,12}{1,8}{2,12}{3,14}\n",
                                    "City", "Year", "Population", "Change (%)");
      Console.WriteLine(header);
      string output;      
      foreach (var city in cities) {
         output = String.Format("{0,-12}{1,8:yyyy}{2,12:N0}{3,8:yyyy}{4,12:N0}{5,14:P1}",
                                city.Item1, city.Item2, city.Item3, city.Item4, city.Item5,
                                (city.Item5 - city.Item3)/city.Item3 * 1.0);
         Console.WriteLine(output);
      }
   }
}
// The example displays the following output:
//    City            Year  Population    Year  Population    Change (%)
//    
//    Los Angeles     1940   1,504,277    1950   1,970,358        31.0 %
//    New York        1940   7,454,995    1950   7,891,957         5.9 %
//    Chicago         1940   3,396,808    1950   3,620,962         6.6 %
//    Detroit         1940   1,623,452    1950   1,849,568        13.9 %


See Also

Reference

Other Resources

Change History

Date

History

Reason

September 2011

Added the Remarks section.

Customer feedback.

Community Content

Thomas Lee
Passing null arguments is safe
If any arguments object is a null reference (Nothing in Visual Basic), then the format item is replaced by the empty string ("").

The current documentation has this statement in format index section, but it should be in args section as well

Sebastian Godelet
Link to Composite formatting
I ran into the same problem, so here the link I (and probably others) are looking for: http://msdn.microsoft.com/en-us/library/txafckwd.aspx