C# String Interpolation — Complete Guide
In this tutorial, you'll learn about C# String Interpolation. We cover key concepts, practical examples, and best practices.
You build a string with dynamic values using concatenation or String.Format. The code is hard to read because the values are separated from the text. String interpolation lets you embed expressions directly inside the string.
Wrong
string name = "Alice";
int age = 30;
string message = "User " + name + " is " + age + " years old.";
// or
string message = string.Format("User {0} is {1} years old.", name, age);
Output: "User Alice is 30 years old." — but the format is hard to scan because values and placeholders are separated.
Right
string name = "Alice";
int age = 30;
string message = $"User {name} is {age} years old.";
Output: "User Alice is 30 years old.".
Interpolated strings support expressions, formatting, and alignment:
double price = 19.99;
int quantity = 3;
string result = $"Total: {price * quantity:C}"; // "$59.97"
string aligned = $"|{"Name",-10}|{"Price",10}|"; // "|Name | Price|"
Prevention
- Use
$""string interpolation instead of concatenation orString.Format. - Use
$""with@""(verbatim) for multi-line:$@"...". - Use
$""with""""(raw string literal) for JSON/templates. - Specify format after
:like{value:N2},{value:C},{value:X}. - Specify alignment like
{value,10}or{value,-10}. - Use
{{and}}for literal braces:$"{{ {value} }}"produces"{ 42 }". - Use
string.Createfor high-performance interpolation in hot paths.
Common Mistakes with string interpolation
- Forgetting that lazy evaluation defers computation until the value is forced, causing space leaks with unevaluated thunks
- Using
returnto exit a function early instead of wrapping a pure value in the monad - Mixing let bindings with <- bindings in do notation, producing type errors
These mistakes appear frequently in real-world CSHARP code. DodaTech's contributors have identified these patterns through analysis of open-source projects and production systems.
Practice Exercise
Write a pure function that safely divides two integers using Maybe, then test it with edge cases like division by zero and negative numbers.
This exercise reinforces the concepts covered in this guide. Try implementing it before checking online solutions.
FAQ
String interpolation is used throughout DodaTech's logging and reporting infrastructure. For more C#, visit DodaTech.
Built by the developers of DodaTech
Doda Browser, DodaZIP & Durga Antivirus Pro