Select Page

A batch report needs formatted text for every row, but it does not need a separate string object for every row. Pass an interpolated expression directly to the .NET 10 StringBuilder.Append overload, then create the finished string once. For a single message, ordinary interpolation remains a useful default.

This tutorial builds a small amount report with explicit formatting and input validation. The examples were compiled and checked with .NET SDK 10.0.402, targeting net10.0 with C# 14.0. They use only the base class library.

Run each example

With the .NET 10 SDK installed, create a console project using dotnet new console --framework net10.0. In that project, replace Program.cs with one complete example below, then run dotnet run. Each example stands alone. See .NET CLI run documentation.

Reassigning a string leaves earlier references unchanged

A string is immutable. Appending text with += assigns a new combined string to the variable; it does not change the string referenced by another variable. This matters when repeatedly growing a result in a loop. See Microsoft’s explanation of string immutability.

using System;

string current = "Draft";
string saved = current;
current += " ready";
Console.WriteLine(saved);
Console.WriteLine(current);
Draft
Draft ready

The saved value is still Draft. For a report assembled across many iterations, use a mutable buffer rather than repeatedly assigning a larger combined string.

Format one result with an explicit culture

Interpolation uses the current culture by default. A decimal point can therefore become a comma. The F2 format requests two fractional digits; it does not select a culture. Pass the culture to string.Create when your text needs an explicit convention. This overload is available from .NET 6. See the interpolation reference.

using System;
using System.Globalization;

CultureInfo.CurrentCulture = CultureInfo.GetCultureInfo("fr-FR");
decimal total = 12.5m;
string display = $"total={total:F2}";
string stored = string.Create(CultureInfo.InvariantCulture, $"total={total:F2}");
Console.WriteLine(display);
Console.WriteLine(stored);
total=12,50
total=12.50

The first line follows French formatting; the second uses the invariant culture. Keep local conventions for text intended for local readers. Use an explicit agreed convention for report fields that another system will consume. Put :F2 inside the interpolation instead of calling ToString on the decimal first; the latter asks for a separately formatted string before the surrounding message is built.

Append report rows directly to the builder

The next program accepts nonnegative amounts written with an invariant decimal point. Its NumberStyles.AllowDecimalPoint policy excludes signs, whitespace, currency symbols and group separators. decimal.TryParse reports failure for rejected input instead of throwing a parse exception. See Decimal.TryParse and its style/provider overload.

using System;
using System.Globalization;
using System.Text;

CultureInfo.CurrentCulture = CultureInfo.GetCultureInfo("fr-FR");
string?[] inputs = { "12.50", "0", "oops", "", null, "-1", "2.5", "1,000", "79228162514264337593543950336" };
var report = new StringBuilder();

for (int i = 0; i < inputs.Length; i++)
{
    if (!decimal.TryParse(inputs[i], NumberStyles.AllowDecimalPoint,
        CultureInfo.InvariantCulture, out decimal total))
    {
        report.Append(CultureInfo.InvariantCulture, $"row={i + 1}; invalid amount");
    }
    else
    {
        report.Append(CultureInfo.InvariantCulture, $"row={i + 1}; total={total:F2}");
    }
    report.Append('\n');
}

string result = report.ToString();
Console.Write(result);
row=1; total=12.50
row=2; total=0.00
row=3; invalid amount
row=4; invalid amount
row=5; invalid amount
row=6; invalid amount
row=7; total=2.50
row=8; invalid amount
row=9; invalid amount

Zero is valid. Text, empty/null values, the negative sign, a comma separator and a value exceeding the decimal range produce an error row. Formatting with F2 is a display choice: this parser does not enforce a two-digit fractional input limit, and formatting can round values. Add a separate precision policy if your application requires one.

Each Append call receives the interpolated expression directly. The provider-and-interpolated-handler overload lets the compiler pass a handler that appends the parts to the builder, without first constructing a complete row string. If you assign the interpolation to a string variable first and then append that variable, you have already requested the row string.

The official .NET 10 StringBuilder implementation shows the handler appending literals and formatting supported values into builder storage, with temporary formatting space when necessary. This is not an allocation-free guarantee: the builder and its storage require memory, formatting paths vary, and ToString() creates the final report string here. The tests check behavior and output; they do not measure allocation counts or speed.

The program appends a literal line-feed character for consistent report output. It calls ToString() after the loop because the goal is one finished report. Calling it inside the loop would request intermediate snapshots.

Adapt the report

Change the input "2.5" to "3.75" and run again. Row 7 becomes row=7; total=3.75; every other row stays the same. An empty input array produces no text. Both variations were also checked.

Choose interpolation for one message and direct builder appends when accumulating a result across iterations. Keep the input policy, output culture and final string creation visible in the code, and measure your actual workload before making performance claims.

For related tasks, continue with C# Station’s string-to-integer parsing tutorial, joining and splitting tutorial, or empty, null and whitespace checks.

Share This