✨ More Than Just ${variable}
String interpolation can format numbers, align text, use expressions, and even span multiple lines. Level up your strings.
📝 Formatting Numbers
double price = 1234.5678;
string formatted = $"Price: {price:C2}"; // $1,234.57
formatted = $"Percent: {0.1234:P1}"; // 12.3%
formatted = $"{price:N0}"; // 1,235
formatted = $"{price:F2}"; // 1234.57
formatted = $"{price:E4}"; // 1.2346E+003
// Date formatting
DateTime now = DateTime.Now;
formatted = $"{now:yyyy-MM-dd}"; // 2024-01-15
formatted = $"{now:MMMM dd, yyyy}"; // January 15, 2024
formatted = $"{now:HH:mm:ss}"; // 14:30:45
🎯 Alignment and Expressions
// Right/left alignment
string[] names = ["Alice", "Bob", "Charlie"];
foreach (var name in names) {
Console.WriteLine($"{name,10}"); // Right-aligned, width 10
Console.WriteLine($"{name,-10}"); // Left-aligned, width 10
}
// Expressions inside interpolation
int x = 10, y = 20;
string result = $"Sum: {x + y}, Product: {x * y}";
// Ternary operator
bool isAdmin = true;
string role = $"User is {(isAdmin ? "Admin" : "User")}";
// Conditional formatting
double temperature = 25.5;
string weather = $"Temp: {temperature:F1}°C {(temperature > 30 ? "Hot!" : "Nice")}";
// Multi-line strings
string sql = $@"
SELECT * FROM users
WHERE id = {userId}
AND status = 'active'";
✅ Culture-Specific Formatting
// Invariant culture (for serialization)
string json = $"{{ "price": {price.ToString(CultureInfo.InvariantCulture)} }}";
// Specific culture
var culture = new CultureInfo("de-DE");
string germanPrice = $"Price: {price.ToString("C2", culture)}"; // 1.234,57 €
// Create interpolated string handler for performance
public static void Log(LogLevel level, [InterpolatedStringHandlerArgument("")] ref MyInterpolatedStringHandler handler)
{
if (IsEnabled(level))
Console.WriteLine(handler.ToString());
}
“Used to concatenate strings with +. Switched to interpolation. Code is cleaner, faster, and formatting is built-in. Cannot go back.”
