String.Format Method (String, Object[])
Updated: August 2009
Replaces the format item in a specified string with the string representation of a corresponding object in a specified array.
Assembly: mscorlib (in mscorlib.dll)
Parameters
- format
- Type: System.String
A composite format string (see Remarks).
- args
- Type: System.Object[]
An object array that contains zero or more objects to format.
Return Value
Type: System.StringA copy of format in which the format items have been replaced by the string representation of the corresponding objects in args.
| Exception | Condition |
|---|---|
| ArgumentNullException |
format or args is null. |
| FormatException |
format is invalid. -or- The index of a format item is less than zero, or greater than or equal to the length of the args array. |
This method uses the composite formatting feature of the .NET Framework to convert the value of an object to its text representation and embed that representation in a string. The .NET Framework provides extensive formatting support, which is described in greater detail in the following formatting topics.
-
For more information about the composite formatting feature supported by methods such as Format, AppendFormat, and some overloads of WriteLine, see Composite Formatting.
-
For more information about numeric format specifiers, see Standard Numeric Format Strings and Custom Numeric Format Strings.
-
For more information about date and time format specifiers, see Standard Date and Time Format Strings and Custom Date and Time Format Strings.
-
For more information about enumeration format specifiers, see Enumeration Format Strings.
-
For more information about formatting, see Formatting Types and Formatting Overview.
The format parameter consists of zero or more runs of text intermixed with zero or more indexed placeholders, called format items, that correspond to an object in the parameter list of this method. The formatting process replaces each format item with the string representation of the corresponding object.
The syntax of a format item is as follows:
{index[,length][:formatString]}
Elements in square brackets are optional. The following table describes each element. For more information about the composite formatting feature, including the syntax of a format item, see Composite Formatting.
|
Element |
Description |
|---|---|
|
index |
The zero-based position in the parameter list of the object to be formatted. If the object specified by index is null, the format item is replaced by String.Empty. If there is no parameter in the index position, a FormatException is thrown. |
|
,length |
The minimum number of characters in the string representation of the parameter. If positive, the parameter is right-aligned; if negative, it is left-aligned. |
|
:formatString |
A standard or custom format string that is supported by the object to be formatted. Possible values for formatString are the same as the values supported by the object's ToString(format) method. If formatString is not specified and the object to be formatted implements the IFormattable interface, null is passed as the value of the format parameter that is used as the IFormattable.ToString format string. |
Note:
|
|---|
|
For the standard and custom format strings used with date and time values, see Standard Date and Time Format Strings and Custom Date and Time Format Strings. For the standard and custom format strings used with numeric values, see Standard Numeric Format Strings and Custom Numeric Format Strings. For the standard format strings used with enumerations, see Enumeration Format Strings. |
The leading and trailing brace characters, '{' and '}', are required. To specify a single literal brace character in format, specify two leading or trailing brace characters; that is, "{{" or "}}".
If the value of format is, "Thank you for your purchase of {0:####} copies of Microsoft®.NET (Core Reference).", and arg[0] is an Int16 with the value 123, then the return value will be:
"Thank you for your purchase of 123 copies of Microsoft®.NET (Core Reference)."
If the value of format is, "Brad's dog has {0,-8:G} fleas.", arg[0]is an Int16 with the value 42, (and in this example, underscores represent padding spaces) then the return value will be:
"Brad's dog has 42______ fleas."
The following example creates a string that contains data on the high and low temperature on a particular date. The composite format string has five format items in the C# example and six in the Visual Basic example. Two of the format items define the width of their corresponding value's string representation, and the first format item also includes a standard date and time format string.
using System; public class Example { public static void Main() { DateTime date1 = new DateTime(2009, 7, 1); TimeSpan hiTime = new TimeSpan(14, 17, 32); decimal hiTemp = 62.1m; TimeSpan loTime = new TimeSpan(3, 16, 10); decimal loTemp = 54.8m; string result1 = String.Format("Temperature on {0:d}:\n{1,11}: {2} degrees (hi)\n{3,11}: {4} degrees (lo)", date1, hiTime, hiTemp, loTime, loTemp); Console.WriteLine(result1); Console.WriteLine(); string result2 = String.Format("Temperature on {0:d}:\n{1,11}: {2} degrees (hi)\n{3,11}: {4} degrees (lo)", new object[] { date1, hiTime, hiTemp, loTime, loTemp }); Console.WriteLine(result2); } } // The example displays the following output: // Temperature on 7/1/2009: // 14:17:32: 62.1 degrees (hi) // 03:16:10: 54.8 degrees (lo) // Temperature on 7/1/2009: // 14:17:32: 62.1 degrees (hi) // 03:16:10: 54.8 degrees (lo)
Windows 7, Windows Vista, Windows XP SP2, Windows XP Media Center Edition, Windows XP Professional x64 Edition, Windows XP Starter Edition, Windows Server 2008 R2, Windows Server 2008, Windows Server 2003, Windows Server 2000 SP4, Windows Millennium Edition, Windows 98, Windows CE, Windows Mobile for Smartphone, Windows Mobile for Pocket PC, Xbox 360, Zune
The .NET Framework and .NET Compact Framework do not support all versions of every platform. For a list of the supported versions, see .NET Framework System Requirements.
If you change the int[] to an object[], the error goes away and the format works as desired. Is this a bug with .ToString() perhaps?
Example:
string.Format("{0:D2}{1:D5}", new int[] { 11, 123} ); //Will generate the exception
string.Format("{0:D2}{1:D5}", new object[] { 11, 123} ); //Will output 1100123Why the FormatException?
If we use ILDasm to look at the IL generated by the C# compiler (or the VB compiler -- its IL is identical), we'd see that the first line of code calls the String.Format(String, Object) method, while the second calls the String.Format(String, Object[]) method. The FormatException is thrown by the first method call because the second format item specifies that its value comes from the string representation of the second argument in the argument list, but because of the compiler overload resolution, there is only a single argument. The compiler selects the incorrect overload because no implicit conversion from an integer array to an object array exists. As it happens, no explicit conversion exists, either.
So if you want to call the String.Format(String, Object[]) method, you'll have to handle the conversion yourself. The following code uses a lambda expression to do that:
string.Format("{0:D2} {1:D5}", Array.ConvertAll(new int[] { 11, 123}, x => (object) x));
I hope that this helps to answer your question.
--Ron Petrusha
Common Language Runtime User Education
Microsoft Corporation
- 9/29/2011
- Barrakoda
- 10/3/2011
- R Petrusha - MSFT
You can download the cheat sheet at:
http://wwww.dylanbeattie.net/cheatsheets/
Steve's article is at
http://blog.stevex.net/string-formatting-in-csharp/
- 9/18/2010
- Dylan Beattie
- 10/11/2010
- Thomas Lee
I have an array like this:
object[] args
and need to insert those args in a string, for example:
Help from more experienced C# users is needed! Thanks
The ParamArray Attribute and the Method Call
Note that the ParamArray attribute is applied to the args parameter. (See http://msdn.microsoft.com/en-us/library/system.paramarrayattribute.aspx for documentation on the ParamArrayAttribute class.) This means that the arguments can be specified to the method in either of two forms: either as a comma-delimited list of values, or as an array. So both
str = String.Format("Her name is {0} and she's {1} years old", args);
and
str = String.Format("Her name is {0} and she's {1} years old", args[0], args[1]);
as well as
string name;
int age;
str = String.Format("Her name is {0} and she's {1} years old", name, age);
all compile and execute successfully.
- 9/16/2009
- Fabio Milheiro
- 9/21/2009
- R Petrusha - MSFT
Note: