How to Format String in C#: Simple Syntax and Examples
In C#, you can format strings using
string interpolation with $"...", the String.Format() method, or composite formatting with placeholders like {0}. These methods let you insert variables and control how values appear inside strings easily.Syntax
There are three common ways to format strings in C#:
- String Interpolation: Use
$"...{variable}..."to embed variables directly. - String.Format method: Use
String.Format("...{0}...", value)with placeholders. - Composite Formatting: Use placeholders like
{index[,alignment][:formatString]}inside strings.
csharp
string name = "Alice"; int age = 30; // String Interpolation string s1 = $"Name: {name}, Age: {age}"; // String.Format method string s2 = String.Format("Name: {0}, Age: {1}", name, age); // Composite Formatting with alignment and format string s3 = String.Format("Name: {0,-10} Age: {1:D3}", name, age);
Example
This example shows how to use string interpolation and String.Format to create formatted strings with variables.
csharp
using System; class Program { static void Main() { string product = "apple"; double price = 1.2345; int quantity = 5; // Using string interpolation string message1 = $"You bought {quantity} {product}s for {price:C2} each."; // Using String.Format string message2 = String.Format("You bought {0} {1}s for {2:C2} each.", quantity, product, price); Console.WriteLine(message1); Console.WriteLine(message2); } }
Output
You bought 5 apples for $1.23 each.
You bought 5 apples for $1.23 each.
Common Pitfalls
Common mistakes when formatting strings in C# include:
- Forgetting the
$before the string when using interpolation. - Using incorrect placeholder indexes in
String.Format. - Not matching the number of placeholders with the number of arguments.
- Misusing format specifiers or alignment syntax.
csharp
string name = "Bob"; int score = 95; // Wrong: missing $ for interpolation // string wrong1 = "Name: {name}, Score: {score}"; // prints placeholders literally // Correct: string right1 = $"Name: {name}, Score: {score}"; // Wrong: placeholder index mismatch // string wrong2 = String.Format("Name: {0}, Score: {1}", name); // throws error // Correct: string right2 = String.Format("Name: {0}, Score: {1}", name, score);
Quick Reference
| Method | Syntax | Description |
|---|---|---|
| String Interpolation | $"Hello, {name}!" | Embed variables directly inside strings. |
| String.Format | String.Format("Hello, {0}!", name) | Use placeholders with index numbers. |
| Composite Formatting | "{0,-10} {1:C2}" | Format alignment and numeric formats. |
Key Takeaways
Use string interpolation with $"...{variable}..." for simple and readable formatting.
String.Format allows flexible formatting with numbered placeholders.
Always match placeholders with the correct number of arguments to avoid errors.
Use format specifiers to control number, date, and alignment display.
Remember to prefix strings with $ when using interpolation to embed variables.