C# string.Format

Format

String.Format creates strings from a pattern and values. It is a static method. It receives a format string that specifies where the following arguments should inserted. The format string uses substitution markers.

Static MethodFramework: NET

Notes:Many methods in the .NET Framework use format syntax. These include string.Format, Console.WriteLine, ToString and AppendFormat.

Example

Program

This example shows the use of the string.Format method to combine three strings with formatting options. The format string itself is the first argument to the string.Format method and it is specified as a string literal.

The position markers are specified to the left of the colons. The "0", "1:", and "2:" indicate where the first, second and third arguments are inserted. The exact format specification is after the ":" and in between the { } brackets.

String Literal
Based on:

.NET 4.5

Program that uses string.Format: C#

using System;

class Program
{
    static void Main()
    {
	//
	// Declare three variables that we will use in the format method.
	// ... The values they have are not important.
	//
	string value1 = "Dot Net Perls";
	int value2 = 10000;
	DateTime value3 = new DateTime(2007, 11, 1);
	//
	// Use string.Format method with four arguments.
	// ... The first argument is the formatting string.
	// ... It specifies how the next three arguments are formatted.
	//
	string result = string.Format("{0}: {1:0.0} - {2:yyyy}",
	    value1,
	    value2,
	    value3);
	//
	// Write the result.
	//
	Console.WriteLine(result);
    }
}

Output

Dot Net Perls: 10000.0 - 2007
Main method

We see three variables declared and initialized in the start of the Main method. These variables are used in the next call to string.Format. The first argument to the string.Format method is a format string.

The resulting string contains extra formatting between the arguments. The "0.0" part of the format string specifies how the integer is displayed. The "yyyy" part specifies that only the four-digit year of the date should be displayed.

Number formats

Percentage symbol

To continue, you can specify that a value type such as a double can be formatted inside the string.Format method based on the format string. A format string is the first argument to string.Format.

Note:The format string in this example uses the 0:0.0% syntax. This means that the second argument is formatted with the pattern 0.0%.

Program that uses string.Format with number: C#

using System;

class Program
{
    static void Main()
    {
	//
	// Format a ratio as a percentage string.
	// ... You must specify the percentage symbol in the format string.
	// ... It will multiply the value by 100.
	//
	double ratio = 0.73;
	string result = string.Format("string = {0:0.0%}",
	    ratio);
	Console.WriteLine(result);
    }
}

Output

string = 73.0%

In this example, the 0.0% part of the format string specifies the exact number of digits that are required. Note that the 0.0% can have as many digits before the decimal place as necessary, but only one after the decimal place.

Tip:The percentage symbol will result in the number being logically multiplied by 100.

Custom Numeric Format Strings: MSDN

Padding

Padding: right and left

Padding can be used with strings. This can be expressed declaratively in formatting strings. Padding indicates that you are inserting a variable number of characters at the left or right of the string to reach a specified length.

Tip:Instead of the PadLeft and PadRight methods, you can use the string.Format method with special substitutions.

PadRight, PadLeft
Program that uses string.Format for padding: C#

using System;

class Program
{
    static void Main()
    {
	//
	// The constant formatting string.
	// ... It specifies the padding.
	// ... A negative number means to left-align.
	// ... A positive number means to right-align.
	//
	const string format = "{0,-10} {1,10}";
	//
	// Construct the strings.
	//
	string line1 = string.Format(format,
	    100,
	    5);
	string line2 = string.Format(format,
	    "Carrot",
	    "Giraffe");
	//
	// Write the formatted strings.
	//
	Console.WriteLine(line1);
	Console.WriteLine(line2);
    }
}

Output

100                 5
Carrot        Giraffe
Syntax

For declaring padding inside a format string, use the comma character followed by the padding size. You can use a negative padding size to add padding to the right, which will left-align the text.

Also:You can use a positive padding size to add padding to the left. This will right-align the string.

ToString

String type

Sometimes, you need to just format a single number, like an integer or long. In this case, you don't need to use string.Format. You can just use the ToString virtual method. This reduces some overhead.

ToString
Program that uses string.Format and ToString: C#

using System;

class Program
{
    static void Main()
    {
	int value = 123;
	string a = string.Format("{0:0000}", value); // Too complex
	string b = value.ToString("0000"); // Simpler
	Console.WriteLine(a);
	Console.WriteLine(b);
    }
}

Output

0123
0123

FormatException

A FormatException is being thrown. How can you solve this problem? System.FormatException is thrown by methods that receive format strings and substitutions. We see one program that causes it.

Substitution markers

{0}
{1}
{2}
Question

Format strings use substitution markers. The arguments after the format string are placed in those markers in the same order. But what happens if the format string has too many markers?

Program that throws an exception: C#

using System;

class Program
{
    static void Main()
    {
	Console.WriteLine("{0} {2}", "x");
    }
}

Output

Unhandled Exception: System.FormatException:
    Index (zero based) must be greater than or equal to zero and less
    than the size of the argument list.
Warning: exclamation mark

Answer. The System.FormatException is thrown because the {2} substitution marker was not found in the argument list. If more arguments were provided, the program would not throw an exception.

Tip:To fix the program, you could remove the substitution marker {2} or add two more arguments.

Tip 2:Whenever you encounter a FormatException, it is worthwhile to check substitution markers and argument lists for formatting methods.

Dates

Time

The DateTime struct is a value type that is an abstract data type for any possible date and time. The string.Format method can be used with DateTime arguments and these will be inserted into the substitution markers.

Note:We introduce a thorough exploration of the string.Format and DateTime formatting strings.

DateTime Format

File names

Path type

Many programs need to create files dynamically. The files often need to have file names that are based on some characteristic. For example, a logging file can have a file name that is based on the exact date and time it was written.

The string.Format method provides a way to express this functionality in a clear way. You can use the string.Format method with substitutions to create the file names based on state variables.

Filename, DateTime

StringBuilder

StringBuilder

The StringBuilder type presents a method called AppendFormat. The AppendFormat method receives a formatting string and also the arguments to the formatting string, which are placed in the substitution markers.

Caution:For performance work, the AppendFormat method is not ideal. It can however lead to clearer code.

StringBuilderAppendFormat

Console.WriteLine

Console screenshot

Console programs can use formatting strings directly inside the Console.Write and Console.WriteLine methods. When using Visual Studio, type Console.WriteLine and then scroll through the IntelliSense popup to find these overloads.

Then:You can call Console.WriteLine with the same arguments as the string.Format method receives. It will call string.Format.

Console.WriteLine

Implementation

Format

In the base class library, the string.Format method uses a param argument, which is a variable parameter list. This results in an array allocation on each invocation of the method. We discover more about the params keyword here.

Params

Substitution processing. Internally, the string.Format method uses the StringBuilder type, which contains a mutable character buffer. It estimates a capacity based on a heuristic in the StringBuilder constructor.

Next:The AppendFormat method is called to process the substitutions themselves.

Finally:The ToString method is called. It does not normally require a copy to be made.

StringBuilder Capacity

Summary

The string.Format method provides a way to insert argument strings and separators together. It supports specifying display options for each argument. We combined several strings and format dates.


C#: String