String interpolation in C# is a clean way to insert variables and expressions directly inside a string. Instead of joining many pieces of text with the + operator, you can write a readable string and place values inside braces. This makes formatted output easier to write, easier to read, and less error-prone.
String interpolation is commonly used in console output, log messages, error messages, UI labels, reports, file names, API responses, and debugging text. It is one of the most useful everyday features in modern C# because it keeps text formatting close to natural language.
What Is String Interpolation in C#?
String interpolation allows you to embed variables and expressions inside a string by prefixing the string with $ and placing expressions inside curly braces.
string name = "Aman";
int age = 22;
Console.WriteLine($"{name} is {age} years old");
The output is:
Aman is 22 years old
String interpolation turns variables and expressions into readable formatted text.
Basic Syntax of String Interpolation
$"Text {expression} more text"
The $ symbol must appear before the opening quote. Expressions inside braces are evaluated and converted to string form.
String Interpolation vs Concatenation
Before interpolation, developers often used concatenation.
string name = "Riya";
int score = 95;
Console.WriteLine(name + " scored " + score + " marks");
With interpolation, the same output becomes easier to read.
Console.WriteLine($"{name} scored {score} marks");
Both approaches can work, but interpolation is usually better for formatted text because the final sentence is visible directly in the code.
Using Expressions Inside Interpolated Strings
You are not limited to simple variables. You can place expressions inside the braces.
int a = 10;
int b = 5;
Console.WriteLine($"Sum = {a + b}");
Console.WriteLine($"Product = {a * b}");
The expressions are evaluated first, and then their results are inserted into the string.
Calling Methods Inside Interpolation
Method calls can also be used inside interpolated strings.
string city = "pune";
Console.WriteLine($"City: {city.ToUpper()}");
This prints the uppercase version of the city name. Avoid putting very complex logic inside interpolation, because it can reduce readability.
Formatting Numbers
String interpolation supports format specifiers. These are useful for displaying currency, percentages, decimal places, dates, and aligned output.
decimal price = 1499.5m;
Console.WriteLine($"Price: {price:C}");
The :C format specifier displays the value as currency based on culture settings.
double value = 12.34567;
Console.WriteLine($"Value: {value:F2}");
The F2 format displays two digits after the decimal point.
Formatting Dates
Date and time values can also be formatted inside interpolated strings.
DateTime today = DateTime.Now;
Console.WriteLine($"Date: {today:dd-MM-yyyy}");
Console.WriteLine($"Time: {today:HH:mm:ss}");
This is useful for logs, reports, receipts, filenames, and user-facing messages.
Alignment in Interpolated Strings
You can align values by adding a comma and width inside the braces.
Console.WriteLine($"{"Name",-10} {"Marks",5}");
Console.WriteLine($"{"Aman",-10} {95,5}");
Console.WriteLine($"{"Riya",-10} {88,5}");
A positive width aligns text to the right. A negative width aligns text to the left. This is useful for simple table-like console output.
Escaping Braces
Curly braces have special meaning in interpolated strings. If you want to print actual braces, use double braces.
int value = 10;
Console.WriteLine($"Value is {{ {value} }}");
This is useful when generating text that contains JSON-like structures, templates, or mathematical notation.
Interpolated Verbatim Strings
You can combine interpolation with verbatim strings using $@ or @$. This is useful for file paths and multi-line strings.
string user = "Admin";
string path = $@"C:\Users\{user}\Documents";
Console.WriteLine(path);
The string can include backslashes naturally while still allowing variable insertion.
String Interpolation vs string.Format
Before interpolation became common, string.Format() was often used for formatted text. It still works, but interpolation is usually easier to read because the value appears exactly where it will be displayed.
string name = "Aman";
int marks = 91;
string oldStyle = string.Format("{0} scored {1} marks", name, marks);
string newStyle = $"{name} scored {marks} marks";
In the string.Format() version, you must match placeholder numbers with argument positions. In interpolation, the variable names are visible directly in the sentence.
Practical Uses of String Interpolation
- Printing console messages.
- Creating log entries.
- Building user-facing status messages.
- Formatting dates and prices.
- Creating simple file names.
- Displaying validation errors.
- Showing variable values while debugging.
Interpolation is not only a beginner convenience. It appears constantly in production code because readable text generation is needed in nearly every application.
Culture-Sensitive Formatting
Some formatted values depend on culture settings. Currency, dates, decimal separators, and number grouping can look different depending on the current culture. This is important when building applications for users in different regions.
decimal amount = 1500.75m;
Console.WriteLine($"Amount: {amount:C}");
The currency symbol and number formatting can vary based on culture. For internal logs or machine-readable text, use explicit culture-aware formatting when consistency is required.
Raw Interpolated Strings
Modern C# allows raw interpolated strings. These are useful when generating multi-line text that contains quotes, braces, JSON, SQL, or markup-like content.
string name = "Alex";
string json = $"""
{
"name": "{{name}}",
"active": true
}
""";
The number of $ symbols controls how many braces are required for interpolation. This gives more control when the text itself contains braces.
Interpolation in Logging
String interpolation is useful for simple debug messages, but in structured logging systems, you may need message templates instead of immediate string interpolation. Message templates preserve named values for filtering and analysis. For basic learning and console apps, interpolation is fine. For larger backend systems, follow the logging framework’s recommended pattern.
Readable Expressions Inside Braces
Interpolation allows expressions, but it should not become a place for complicated logic. If the expression is long, compute it first and then interpolate the result. This keeps the string readable.
int obtained = 450;
int total = 500;
double percentage = obtained * 100.0 / total;
Console.WriteLine($"Percentage: {percentage:F2}%");
This is easier to maintain than placing a long formula directly inside the braces.
Interpolation with Null Values
If an interpolated expression evaluates to null, it becomes an empty string in the final output. This can be convenient, but it can also hide missing data if you expected a visible value.
string? name = null;
Console.WriteLine($"Name: {name}");
If missing data should be shown clearly, combine interpolation with the null-coalescing operator.
Console.WriteLine($"Name: {name ?? "Unknown"}");
Escaping Quotes in Interpolated Strings
If the text itself needs double quotes, you can escape them with a backslash or use a raw string style when the content is larger.
string product = "Laptop";
Console.WriteLine($"Selected product: \"{product}\"");
Debugging with Interpolated Strings
Interpolation is useful while debugging because you can quickly print variable names and values in a readable message.
int count = 42;
string status = "Ready";
Console.WriteLine($"Debug: count={count}, status={status}");
This style is simple and effective for small console programs. In larger applications, proper logging tools are usually better.
String Interpolation Feature Summary
| Feature | Example | Use |
|---|---|---|
| Variable insertion | {name} | Insert variable values. |
| Expression insertion | {a + b} | Insert calculated results. |
| Formatting | {price:C} | Format numbers, dates, and currency. |
| Alignment | {name,-10} | Create aligned console output. |
| Escaped braces | {{ }} | Print actual brace characters. |
Practical Receipt Example
A common practical use of interpolation is building readable output from several values. For example, a small billing program may need to display a product name, quantity, price, and total.
string product = "Keyboard";
int quantity = 2;
decimal unitPrice = 799.50m;
decimal total = quantity * unitPrice;
Console.WriteLine($"Product: {product}");
Console.WriteLine($"Quantity: {quantity}");
Console.WriteLine($"Total: {total:C}");
This keeps each output line clear and avoids long concatenation chains.
When Not to Use Interpolation
String interpolation is not always the right choice. If you are building SQL queries, shell commands, HTML, or URLs from user input, interpolation can create security and correctness problems when used carelessly. In those cases, use parameterized queries, encoders, builders, or framework APIs designed for that specific job.
Interpolation is excellent for readable messages, but it should not replace proper data handling, escaping, or validation in security-sensitive code.
Readability in Larger Methods
In larger methods, interpolation should make the message easier to understand, not harder. If a line contains many expressions, format specifiers, method calls, and conditional logic inside braces, split the work into smaller variables first. This makes debugging easier and lets the final interpolated string read like a simple message.
decimal discountAmount = price * discountRate;
decimal finalPrice = price - discountAmount;
Console.WriteLine($"Final price: {finalPrice:C}");
This style keeps calculations separate from presentation, which is easier to maintain as the program grows.
Interpolation and Localization
For applications translated into multiple languages, avoid scattering hard-coded interpolated sentences everywhere. Different languages may need different word order. In localized applications, message templates and resource files are often better than directly writing every interpolated sentence in code.
Common Mistakes in String Interpolation
- Forgetting the
$before the string. - Using braces incorrectly.
- Putting too much complex logic inside interpolation.
- Forgetting that format specifiers are culture-sensitive in some cases.
- Using concatenation when interpolation would be clearer.
- Not escaping braces when actual braces need to be printed.
Is string interpolation better than concatenation?
For formatted output, string interpolation is usually more readable. Concatenation is still valid for simple joining, but interpolation keeps the final text structure clearer.
Can I use expressions inside string interpolation?
Yes. You can use variables, arithmetic expressions, method calls, properties, and many other expressions inside braces.
How do I print braces in an interpolated string?
Use double braces. Write {{ to print { and }} to print }.
Best Practices for String Interpolation in C#
- Use interpolation for readable formatted messages.
- Keep expressions inside braces simple.
- Use format specifiers for dates, currency, and decimal precision.
- Escape braces properly when generating brace-based text.
- Use verbatim interpolated strings for readable file paths.
- Prefer interpolation over long chains of concatenation.
String interpolation in C# makes text formatting cleaner and more expressive. Once you understand the $"...{ }..." syntax, format specifiers, alignment, and escaping rules, you can write output statements that are both powerful and easy to read.