0
0
CsharpHow-ToBeginner · 3 min read

How to Use Format in C# String: Simple Guide

In C#, use string.Format to insert variables into a string by placing placeholders like {0}, {1}, etc., inside the string. You pass the values as additional arguments, and string.Format replaces the placeholders with those values.
📐

Syntax

The string.Format method uses a format string with placeholders and a list of values to insert. Each placeholder is written as {index[,alignment][:formatString]}, where:

  • index: The zero-based position of the argument to insert.
  • alignment (optional): Specifies the minimum width and alignment of the inserted value.
  • formatString (optional): Defines how to format the value (like number or date formats).
csharp
string formatted = string.Format("Hello, {0}! Today is {1:dddd}.", "Alice", DateTime.Now);
💻

Example

This example shows how to use string.Format to insert a name and a number formatted as currency into a string.

csharp
using System;

class Program
{
    static void Main()
    {
        string name = "Bob";
        double price = 123.45;
        string message = string.Format("Hello, {0}! Your total is {1:C2}.", name, price);
        Console.WriteLine(message);
    }
}
Output
Hello, Bob! Your total is $123.45.
⚠️

Common Pitfalls

Common mistakes include:

  • Using placeholders with indexes that don't match the number of arguments, causing runtime errors.
  • Forgetting to use string.Format and trying to use placeholders directly in strings.
  • Incorrect format strings causing unexpected output.

Always ensure the number of placeholders matches the arguments passed.

csharp
using System;

class Program
{
    static void Main()
    {
        // Wrong: Missing argument for {1}
        // string message = string.Format("Name: {0}, Age: {1}", "Alice"); // Throws exception

        // Right:
        string message = string.Format("Name: {0}, Age: {1}", "Alice", 30);
        Console.WriteLine(message);
    }
}
Output
Name: Alice, Age: 30
📊

Quick Reference

Placeholder SyntaxDescriptionExample
{0}Insert first argument"{0}" => "Alice"
{1:C2}Second argument as currency with 2 decimals"{1:C2}" => "$123.45"
{0,10}First argument right-aligned in 10 spaces"{0,10}" => " Alice"
{0,-10}First argument left-aligned in 10 spaces"{0,-10}" => "Alice "

Key Takeaways

Use string.Format with placeholders like {0}, {1} to insert values into strings.
Placeholders must match the number and order of arguments passed to string.Format.
Format specifiers like :C2 or :dddd control how values appear (currency, date, etc.).
Avoid runtime errors by ensuring all placeholders have corresponding arguments.
Use alignment options to control spacing and text alignment inside formatted strings.