Skip to content
Tutorials Center
My learning

Topics

C# Reference ยท Strings and Text

The CompositeFormat class

Reference for System.Text.CompositeFormat in C#: parse a composite format string once, reuse it with string.Format and spans, and catch format errors early.

A composite format string is text with placeholders such as "Order {0} shipped to {1}". Every call to string.Format parses that text again before it can substitute the arguments. System.Text.CompositeFormat (added in .NET 8) does the parsing once and keeps the result, so repeated formatting skips the parsing step and reports a malformed string at creation time instead of at the first use.

Use it for format strings that are constants or loaded once (log templates, report lines, localized messages) and are formatted many times. For one-off formatting, an interpolated string is simpler and just as fast.

C#
using System.Text;

CompositeFormat Template = CompositeFormat.Parse("Hello, {0}! You have {1} messages.");
string text = string.Format(null, Template, "Ada", 3);

Try it

C# Parse once, format many times

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

C# Errors surface at Parse time

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

Syntax

C#
public sealed class CompositeFormat
{
    public static CompositeFormat Parse([StringSyntax(StringSyntaxAttribute.CompositeFormat)] string format);
    public static bool TryParse(string? format, out CompositeFormat? compositeFormat);

    public string Format { get; }
    public int MinimumArgumentCount { get; }
}

// Consumers
string.Format(IFormatProvider? provider, CompositeFormat format, object?[] args);
string.Format<TArg0, TArg1>(IFormatProvider? provider, CompositeFormat format, TArg0 arg0, TArg1 arg1);
bool MemoryExtensions.TryWrite(this Span<char> destination, IFormatProvider? provider,
                               CompositeFormat format, out int charsWritten, params object?[] args);
StringBuilder.AppendFormat(IFormatProvider? provider, CompositeFormat format, object?[] args);
Name Description
format A composite format string using {index[,alignment][:formatString]} placeholders.
provider Culture rules for numbers, dates and so on. null means the current culture.
args / arg0..argN The values to insert. Generic overloads exist for one to three arguments.
Format The original text you parsed.
MinimumArgumentCount The highest placeholder index plus one: how many arguments formatting needs.

Returns: Parse returns an immutable CompositeFormat. TryParse returns false instead of throwing. The consumers return the formatted string, or bool plus the character count for TryWrite.

Errors / undefined behavior: Parse throws ArgumentNullException for null and FormatException for malformed text. Formatting with fewer arguments than MinimumArgumentCount throws FormatException. Extra arguments are ignored.

Usage notes

  • Store it in a static readonly field. The benefit comes from parsing once and reusing the object. Calling CompositeFormat.Parse inside the hot loop gives you the cost of parsing without the savings.
  • Placeholders are positional. is the first argument. The same index can appear more than once, and indexes need not appear in order.
  • Alignment and format strings still work. {0,-8} pads on the right to eight characters and {1,8:N2} right-aligns a number with two decimals. See C# format specifiers.
  • Pass the culture explicitly. The provider is the first argument of the consuming methods. Use CultureInfo.InvariantCulture for machine-readable text; this site's runner only knows the invariant culture.
  • Prefer interpolation for simple cases. $"Hello {name}" is compiled into efficient code already (an interpolated string handler). CompositeFormat matters when the template is data, such as a string from a resource file or configuration, and cannot be a literal.
  • Analyzer help. The StringSyntax attribute lets editors check the placeholders of a string passed to Parse. Analyzer CA1863 suggests switching string.Format calls with constant formats to CompositeFormat.
  • Thread safety. The object is immutable and safe to share between threads.
  • Not for user-supplied templates without care. Placeholders can read any argument index and format string you give them. Do not let untrusted input choose the template if the arguments contain secrets.