C# StringBuilder AppendFormat() Method

Beginner
5 min read
Updated: Nov 2026
3 examples
StringBuilder

Definition

In C#, StringBuilder.AppendFormat(format, args) adds a message to the end of the builder, after filling in its placeholders. A placeholder is a number in braces, such as {0} for the first value and {1} for the second. This is called composite formatting, the same system used by string.Format.

A placeholder can also carry a format ({0:F2} = two decimals) and an alignment ({0,-8} = 8 characters wide). Unlike string.Format, no separate string is returned: the text goes straight into the builder, which comes back for chaining.

An instance method of StringBuilder (using System.Text;), called as sb.AppendFormat(...). The builder is a mutable buffer that changes in place, unlike an immutable string. It is not thread-safe. The string and IFormatProvider overloads exist in every .NET version. Overloads that take a pre-parsed CompositeFormat were added in .NET 8.

Syntax

Pass a format string and the values. Put an IFormatProvider first to control the culture.

C#
StringBuilder sb = new StringBuilder();
sb.AppendFormat("{0} + {1} = {2}", 2, 3, 5);         // 2 + 3 = 5
sb.AppendFormat(CultureInfo.InvariantCulture,
                " ({0:F1}%)", 12.345);              // " (12.3%)"
CallWhat it does
sb.AppendFormat("{0}", x)Adds x as text in place of {0}.
sb.AppendFormat("{1} {0}", a, b)Placeholders can come in any order and be used more than once.
sb.AppendFormat(inv, "{0:N0}", 1234567)With CultureInfo.InvariantCulture, prints 1,234,567 on every machine.
sb.AppendFormat("{{0}}")Double braces print a literal brace: the result is {0}.

Without a provider, numbers and dates use the current culture. A placeholder with no matching value (such as {1} with one argument) or a broken brace throws FormatException, possibly after some text was already added. A null format throws ArgumentNullException.

Library declarations
C#
public StringBuilder AppendFormat(string format, object? arg0);
public StringBuilder AppendFormat(string format, object? arg0, object? arg1);
public StringBuilder AppendFormat(string format, params object?[] args);
public StringBuilder AppendFormat(IFormatProvider? provider, string format, params object?[] args);
// plus provider versions with 1-3 args, and CompositeFormat versions (.NET 8+)

Parameters

ParameterDescription
providerOptional. Culture rules for numbers and dates, such as CultureInfo.InvariantCulture.
formatRequired. The message with placeholders like {0}, {1:F2}, or {0,5}.
arg0... / argsThe values to fill in. {0} takes the first one, {1} the second, and so on.

Return Value

Return ValueDescription
StringBuilderThe same builder, with the formatted text added at the end.

C# Examples

Example 1 — Fill In Numbered Placeholders

Put a name and an age into a sentence, then reuse a placeholder and swap the order.

C#
using System;
using System.Text;

class Program {
    static void Main() {
        StringBuilder sb = new StringBuilder();
        sb.AppendFormat("{0} is {1} years old.", "Asha", 12);
        Console.WriteLine(sb.ToString());

        sb.Clear();
        sb.AppendFormat("{1} before {0}, then {1} again", "A", "B");
        Console.WriteLine(sb.ToString());
    }
}

How It Works

  1. Match by number. {0} is replaced by "Asha", the first value after the format, and {1} by 12, the second.
  2. Start fresh. sb.Clear() empties the builder, so the second message does not pile onto the first one.
  3. Any order, any number of times. The second format uses {1} twice and {0} once, so B appears twice and A once.
  4. Text outside braces stays. Words like before and then are copied exactly as written.

Example 2 — Dates and Numbers With InvariantCulture

Format a date, a zero-padded number, a large number with group separators, and a price, all in one call with a fixed culture.

C#
using System;
using System.Globalization;
using System.Text;

class Program {
    static void Main() {
        CultureInfo inv = CultureInfo.InvariantCulture;
        StringBuilder sb = new StringBuilder();

        sb.AppendFormat(inv, "{0:yyyy-MM-dd} | {1:D3} | {2:N0} | {3:F2}",
            new DateTime(2026, 1, 5), 7, 1234567, 4.5);

        Console.WriteLine(sb.ToString());
    }
}

How It Works

  1. A fixed culture first. Passing CultureInfo.InvariantCulture as the first argument means commas, dots, and dates look the same on every computer.
  2. Date pattern. {0:yyyy-MM-dd} writes the year, month, and day with dashes, so 5 January 2026 becomes 2026-01-05.
  3. Integer patterns. D3 pads 7 with zeros to three digits (007), and N0 adds group separators with no decimals (1,234,567).
  4. Fixed decimals. F2 always shows two digits after the point, so 4.5 prints as 4.50.

Example 3 — Align Columns, Escape Braces, and Catch a Missing Value

Line up a tiny price table with alignment, print literal braces, and see the exception for a missing value.

C#
using System;
using System.Text;

class Program {
    static void Main() {
        string[] names = { "Tea", "Coffee", "Juice" };
        int[] prices = { 20, 35, 140 };
        StringBuilder row = new StringBuilder();

        for (int i = 0; i < names.Length; i++) {
            row.Clear();
            row.AppendFormat("[{0,-6}|{1,4}]", names[i], prices[i]);
            Console.WriteLine(row.ToString());
        }

        row.Clear();
        row.AppendFormat("{{0}} prints as {0}", "braces");
        Console.WriteLine(row.ToString());

        try {
            row.AppendFormat("{0} and {1}", "only one");
        } catch (FormatException) {
            Console.WriteLine("Missing argument for {1}");
        }
    }
}

How It Works

  1. Negative width pads on the right. {0,-6} makes each name 6 characters wide, so the names line up on the left.
  2. Positive width pads on the left. {1,4} puts spaces in front of each price, so the numbers line up on the right.
  3. Literal braces. {{ and }} print a single { and }. Only the plain {0} is filled in.
  4. Missing value. {1} asks for a second value that was never passed, so FormatException is thrown and caught.

Frequently Asked Questions

It fills placeholders such as {0} and {1} with your values and adds the text to the end of the builder, then returns the same builder.
Same formatting rules. string.Format returns a new string; AppendFormat writes straight into an existing StringBuilder.
Pass CultureInfo.InvariantCulture as the first argument, for example sb.AppendFormat(CultureInfo.InvariantCulture, "{0:F2}", price).
Usually a placeholder number has no matching value, such as {2} when only two values were passed, or a brace is not closed. Use {{ and }} for literal braces.
Both work. sb.Append($"{name}: {score}") reads better; AppendFormat helps when the format comes from a setting or resource file.

Next: AppendJoin()

Add every item of a list or array to the builder with a separator between them.

AppendJoin() tutorial →

About the author

Mari Selvan M P
Mari Selvan M P 🔗

Developer, cloud engineer, and technical writer

  • Experience 12 years building web and cloud systems
  • Focus Full Stack Development, AWS, and Developer Education

I write practical tutorials so students and working developers can learn by doing—from databases and APIs to deployment on AWS.

8 people found this page helpful