String.Format
Learn placeholder-based formatting with String.Format.
String.Format
The String.Format method produces text with placeholders. The first parameter is the format string and the rest are variables: String.Format("{0} years old, in {1}.", age, city).
{0} stands for the first variable and {1} for the second; counting starts at zero. You can repeat placeholders in any order: "{0} and {0}" writes the same value twice. This approach was common before interpolation.
Formatting suffixes
You can add formatting to placeholders with a colon: {0:F2} shows a number with two decimal places, {0:C} shows it as currency. This lets you control the appearance of the output from one place.
For example, String.Format("Amount: {0:C}", 49.5) produces output with the currency symbol. Interpolation shares the same syntax: $"Amount: {price:C}" gives the same result.
Exercise Build a sentence with String.Format
Declare a name variable with the value "Alex". Use String.Format with the format string "{0}, welcome!" to produce "Alex, welcome!" and print it with Console.WriteLine.
Show example solution
Put String.Format("{0}, welcome!", name) inside Console.WriteLine.
Example solution:
using System;
class Program
{
static void Main()
{
string name = "Alex";
Console.WriteLine(String.Format("{0}, welcome!", name));
}
}
Test yourself
-
What is the output of String.Format("{1}-{0}", "a", "b")?
Console.WriteLine(String.Format("{1}-{0}", "a", "b"));- b-a
- a-b
- 1-0
- ab
Show answer
b-a — Correct. {1} picks 'b', {0} picks 'a'.
-
Write the first part
string result = String.Format("____: {0}", "Hello");Show answer
string result = String.Format("Message: {0}", "Hello"); -
Match each placeholder to its parameter
- {0}
- First parameter
- {1}
- Second parameter
- {2}
- Third parameter
- {0} and {0}
- First twice