How to Use string.Format in C# for Formatting Strings
Use
string.Format in C# to create formatted strings by placing numbered placeholders like {0} in a string and passing values to replace them. It returns a new string with the placeholders replaced by the provided values in order.Syntax
The basic syntax of string.Format is:
string.Format(formatString, arg0, arg1, ...)formatStringcontains text with placeholders like{0},{1}, etc.arg0, arg1, ...are the values to insert into the placeholders.
Each placeholder number corresponds to the argument index.
csharp
string.Format("Hello, {0}! You have {1} new messages.", "Alice", 5);
Example
This example shows how to use string.Format to insert a name and a number into a greeting message.
csharp
using System; class Program { static void Main() { string name = "Alice"; int messageCount = 5; string result = string.Format("Hello, {0}! You have {1} new messages.", name, messageCount); Console.WriteLine(result); } }
Output
Hello, Alice! You have 5 new messages.
Common Pitfalls
Common mistakes when using string.Format include:
- Using placeholder numbers that don't match the number of arguments, causing runtime errors.
- Forgetting to escape braces
{or}if you want to show them literally by doubling them{{or}}. - Passing arguments in the wrong order, which leads to incorrect output.
csharp
using System; class Program { static void Main() { // Wrong: Missing argument for {1} // string result = string.Format("{0} scored {1} points.", "Bob"); // Throws exception // Correct: Provide both arguments string correctResult = string.Format("{0} scored {1} points.", "Bob", 42); Console.WriteLine(correctResult); // Showing literal braces string braces = string.Format("Use double braces to show {{ and }}."); Console.WriteLine(braces); } }
Output
Bob scored 42 points.
Use double braces to show { and }.
Quick Reference
Here is a quick reference for string.Format placeholders and usage:
| Placeholder | Description | Example |
|---|---|---|
| {0} | First argument | string.Format("{0}", "Hello") → "Hello" |
| {1} | Second argument | string.Format("{1}", "A", "B") → "B" |
| {{ | Literal open brace | string.Format("{{{{") → "{" |
| }} | Literal close brace | string.Format("}}}}") → "}" |
| {0:N2} | Format number with 2 decimals | string.Format("{0:N2}", 3.14159) → "3.14" |
Key Takeaways
Use string.Format with numbered placeholders like {0}, {1} to insert values into strings.
Make sure the number of placeholders matches the number of arguments to avoid errors.
Double braces {{ and }} show literal braces in the output string.
You can format numbers and dates inside placeholders using format specifiers.
string.Format returns a new formatted string without changing the original.