C# String Interpolation

String interpolation is a C# feature for placing values directly inside a string. Instead of breaking a message into many pieces with +, you write the text once and put expressions inside braces. This makes output, logs, prompts, and formatted reports easier to read and harder to assemble incorrectly.

Overview: How String Interpolation Works

An interpolated string starts with a dollar sign before the opening quote: $"Hello, {name}". The braces contain interpolation expressions. At runtime, C# evaluates each expression, converts the result to text, and inserts it into the final string.

The expression inside braces can be a variable, property access, method call, arithmetic expression, or conditional expression. For example, {price * quantity} is valid because the compiler treats it as an expression, not as plain text. The surrounding characters are normal string content.

Under the hood, interpolation is not magic text replacement performed by the CLR after the program starts. The C# compiler understands interpolated strings and lowers them into ordinary .NET operations. Simple interpolated strings are commonly compiled into calls that concatenate strings or call string.Format-style formatting. Modern C# also uses interpolated string handlers in some contexts, such as logging APIs, so expensive formatting work can sometimes be skipped when the receiving API does not need the message.

The final value is still a string, and strings are immutable. Each completed interpolation creates a string object containing the completed text. If the interpolated expression contains a number, date, Boolean, enum, or custom object, .NET converts it by using formatting rules. By default, that usually means calling ToString(), but interpolation can also include alignment and format strings for more control.

Interpolation is especially useful for console output because the code reads in the same order as the sentence. Compare "Total: " + total with $"Total: {total}". The second version keeps the label and value together and scales better as the message grows.

Syntax

string message = $"Hello, {name}!";
string totalLine = $"Total: {subtotal + tax:F2}";
string column = $"{item,-12}{quantity,4}";
Part Meaning
$ Marks the string literal as interpolated.
"..." The normal string literal delimiters.
{name} Evaluates the expression name and inserts its value.
{value:F2} Applies a format string. F2 prints a number with two decimal places.
{text,10} Right-aligns the value in a field at least 10 characters wide.
{text,-10} Left-aligns the value in a field at least 10 characters wide.
{{ and }} Writes literal braces in the result.

The full placeholder form is {expression[,alignment][:formatString]}. The expression is required. Alignment and format string are optional. Alignment controls spacing; the format string controls how numbers, dates, and other formattable values become text.

Examples

Basic Values in a Sentence

using System;

class Program
{
    static void Main()
    {
        string student = "Maya";
        int completedLessons = 7;
        int totalLessons = 10;

        string message = $"{student} completed {completedLessons} of {totalLessons} lessons.";
        Console.WriteLine(message);
        Console.WriteLine($"Remaining: {totalLessons - completedLessons}");
    }
}

Output:

Maya completed 7 of 10 lessons.
Remaining: 3

The first interpolated string inserts three variables into one sentence. The second uses the arithmetic expression totalLessons - completedLessons directly inside the braces. C# evaluates the expression first, then inserts the result.

Formatting Numbers and Dates

using System;

class Program
{
    static void Main()
    {
        string product = "Notebook";
        int quantity = 3;
        decimal unitPrice = 4.5m;
        DateTime due = new DateTime(2026, 8, 15);

        decimal total = quantity * unitPrice;

        Console.WriteLine($"Item: {product}");
        Console.WriteLine($"Unit price: {unitPrice:F2}");
        Console.WriteLine($"Total: {total:F2}");
        Console.WriteLine($"Due: {due:yyyy-MM-dd}");
    }
}

Output:

Item: Notebook
Unit price: 4.50
Total: 13.50
Due: 2026-08-15

The F2 format string prints a numeric value with exactly two digits after the decimal point. The date format yyyy-MM-dd prints a four-digit year, two-digit month, and two-digit day. Format strings are placed after a colon inside the interpolation braces.

Aligned Console Output

using System;

class Program
{
    static void Main()
    {
        string item1 = "Pens";
        int qty1 = 12;
        decimal total1 = 6m;

        string item2 = "Markers";
        int qty2 = 4;
        decimal total2 = 9.5m;

        Console.WriteLine($"{"Item",-10}{"Qty",5}{"Total",9}");
        Console.WriteLine($"{item1,-10}{qty1,5}{total1,9:F2}");
        Console.WriteLine($"{item2,-10}{qty2,5}{total2,9:F2}");
    }
}

Output:

Item        Qty    Total
Pens         12     6.00
Markers       4     9.50

Alignment is useful for simple text tables. Negative alignment, such as -10, pads on the right and left-aligns the value. Positive alignment, such as 5, pads on the left and right-aligns the value. The field is a minimum width; longer values are not cut off.

Literal Braces and Verbatim Interpolation

using System;

class Program
{
    static void Main()
    {
        string folder = "reports";
        string file = "summary.txt";
        int count = 5;

        string path = $@"C:\Course\{folder}\{file}";
        string jsonLike = $"{{ \"count\": {count} }}";

        Console.WriteLine(path);
        Console.WriteLine(jsonLike);
    }
}

Output:

C:\Course\reports\summary.txt
{ "count": 5 }

The $@ prefix creates an interpolated verbatim string. In a verbatim string, backslashes are ordinary characters, which makes Windows-style paths easier to read. To output literal braces from an interpolated string, double them as {{ and }}.

How It Works Step by Step

  1. The compiler sees the $ prefix and parses the string as an interpolated string instead of a plain literal.
  2. Text outside braces becomes literal string content.
  3. Each placeholder is parsed as a C# expression. Normal type checking still applies, so invalid expressions are compile-time errors.
  4. At runtime, expressions are evaluated from left to right as the final string is built.
  5. If a placeholder has alignment, padding is applied after the value is converted to text.
  6. If a placeholder has a format string, the value is formatted through .NET formatting APIs when the value supports them.
  7. The completed result is a normal immutable string.

Because expressions run when the string is built, avoid putting slow method calls or expressions with side effects inside interpolation when the message may not be needed. For ordinary console output, interpolation is clear and appropriate. For high-volume logging, prefer logging APIs that accept message templates or interpolated string handlers so work can be avoided when a log level is disabled.

Common Mistakes

Forgetting the Dollar Sign

using System;

class Program
{
    static void Main()
    {
        string name = "Nora";
        Console.WriteLine("Hello, {name}!");
        Console.WriteLine($"Hello, {name}!");
    }
}

Output:

Hello, {name}!
Hello, Nora!

Without $, braces have no interpolation meaning. They are just characters in the string. Add the dollar sign before the opening quote when you want C# to evaluate placeholders.

Not Escaping Literal Braces

string text = $"Set notation: {1, 2, 3}";

This does not compile as intended because the compiler treats braces in an interpolated string as placeholder delimiters. Use doubled braces when you want braces in the output.

using System;

class Program
{
    static void Main()
    {
        string text = $"Set notation: {{1, 2, 3}}";
        Console.WriteLine(text);
    }
}

Output:

Set notation: {1, 2, 3}

Depending on Default Formatting for Important Output

using System;

class Program
{
    static void Main()
    {
        decimal amount = 12m / 5m;
        DateTime day = new DateTime(2026, 7, 24);

        Console.WriteLine($"Amount: {amount}");
        Console.WriteLine($"Amount: {amount:F2}");
        Console.WriteLine($"Date: {day}");
        Console.WriteLine($"Date: {day:yyyy-MM-dd}");
    }
}

Output:

Amount: 2.4
Amount: 2.40
Date: 07/24/2026 00:00:00
Date: 2026-07-24

Default formatting can be fine for quick debugging, but user-facing output often needs a predictable shape. Use explicit numeric and date formats when exact presentation matters.

Best Practices

  • Prefer interpolation over long chains of + when building readable messages.
  • Keep placeholder expressions short. Calculate complicated values in variables before the interpolated string.
  • Use explicit format strings for numbers, dates, percentages, and identifiers that need a stable display format.
  • Use alignment for simple console tables, but use real table or UI formatting tools in larger applications.
  • Escape literal braces with {{ and }}.
  • Use $@"..." or @$"..." for interpolated verbatim strings, especially paths or multi-line text.
  • Do not use interpolation as a substitute for parameterized SQL commands. Interpolating user input into SQL is unsafe.
  • Remember that interpolation creates strings. In loops that build one large result, consider StringBuilder or append-form APIs.

Practice Exercises

  1. Create variables for a customer name, order number, and item count. Print one sentence using interpolation.
  2. Store a decimal price and print it with exactly two decimal places using a format string.
  3. Create three product rows and print them in aligned columns: name left-aligned, quantity right-aligned, and total right-aligned with two decimal places.

Summary

  • String interpolation starts with $ and inserts expressions written inside {}.
  • The result of an interpolated string is a normal immutable string.
  • Placeholders can include expressions, alignment, and format strings.
  • Use {value:F2} for fixed decimal places and date formats such as {date:yyyy-MM-dd} for predictable dates.
  • Use doubled braces, {{ and }}, when you need literal braces in the output.
  • Interpolation improves readability, but important output still deserves explicit formatting and safe handling of user input.