How to use string interpolation in C#
String interpolation in C# uses the $ prefix before a string literal, allowing you to embed expressions directly inside curly braces. This is more readable than string.Format() or concatenation.
You can include format specifiers after a colon inside the braces, like {value:C} for currency or {number:F2} for two decimal places.
Interpolated strings are evaluated at compile time and converted to string.Format() calls, making them both efficient and type-safe.
C# Example Code
using System;
public class StringInterpolation
{
public static void Main(string[] args)
{
string name = "Alice";
int age = 30;
// Basic string interpolation
string message = $"My name is {name} and I am {age} years old.";
Console.WriteLine(message);
// With expressions
int a = 10, b = 20;
Console.WriteLine($"Sum: {a + b}, Product: {a * b}");
// Formatting numbers
double price = 49.99;
Console.WriteLine($"Price: {price:C}"); // Currency format
Console.WriteLine($"Price: ${price:F2}"); // Two decimal places
// Formatting dates
DateTime now = DateTime.Now;
Console.WriteLine($"Date: {now:yyyy-MM-dd}");
Console.WriteLine($"Time: {now:HH:mm:ss}");
// Method calls in interpolation
string text = "hello";
Console.WriteLine($"Uppercase: {text.ToUpper()}");
// Alignment and padding
Console.WriteLine($"{"Name",-10} {"Age",5}");
Console.WriteLine($"{name,-10} {age,5}");
// Verbatim interpolated strings
string path = $@"C:\Users\{name}\Documents";
Console.WriteLine($"Path: {path}");
// Conditional expressions
int score = 85;
Console.WriteLine($"Result: {(score >= 60 ? "Pass" : "Fail")}");
}
}