String formatting in C#

Short answer

Use interpolated strings: $"Hello {name}". Add format specifiers after a colon — {value:F2} for two decimals, {value:C} for currency, {value:N0} for thousands separators.

csharp
var name = "Dom";
var views = 5063;
var rating = 4.8;

$"{name} has {views} views"
$"{views:N0}"          // 5,063
$"{rating:F1}"         // 4.8
$"{0.256:P1}"          // 25.6%
$"{19.99:C}"           // $19.99 (culture-dependent)
$"{42:D5}"             // 00042
$"{DateTime.Now:yyyy-MM-dd}"

#Alignment for tables

csharp
$"{name,-15}{views,8:N0}"

Negative pads left (left-aligned), positive pads right. This is how you get columns that line up in console output.

#Culture matters

csharp
$"{19.99:C}"                                          // $ or € or £, per machine
string.Format(CultureInfo.InvariantCulture, "{0:F2}", 19.99)   // always 19.99

For anything written to a file, a URL or an API payload, use InvariantCulture. A German machine formats 19,99 with a comma, which will break your JSON parser.

#StringBuilder for loops

csharp
var sb = new StringBuilder();
foreach (var item in items)
    sb.AppendLine(item.ToString());
var result = sb.ToString();

Strings are immutable, so result += item allocates a whole new string every iteration — quadratic work. StringBuilder mutates a buffer.

For a handful of concatenations the compiler optimises it anyway; the rule matters in loops.

#Raw string literals

csharp
var json = """
    { "title": "Intro", "views": 197 }
    """;

No escaping needed. Prefix with $ for interpolation, and use $$ when the content itself contains braces.