C# String Interpolation
Introduction
String interpolation is a feature in C# that allows you to insert variable values and expressions directly into a string literal. Introduced in C# 6.0, string interpolation provides a more readable and convenient syntax for creating formatted strings compared to traditional string concatenation or string formatting methods.
With string interpolation, you can embed expressions inside string literals using the $
symbol and curly braces {}
. This makes your code more concise and easier to understand, especially when working with complex string construction.
Basic String Interpolation Syntax
To use string interpolation:
- Prefix the string with the
$
character - Place expressions within curly braces
{}
string name = "John";
int age = 30;
// Using string interpolation
string message = $"Hello, my name is {name} and I am {age} years old.";
Console.WriteLine(message);
Output:
Hello, my name is John and I am 30 years old.
Comparing String Interpolation with Other String Operations
Let's compare string interpolation with other methods of combining strings:
string name = "Sarah";
int age = 25;
// String concatenation
string concatString = "Hello, my name is " + name + " and I am " + age + " years old.";
// String.Format method
string formatString = string.Format("Hello, my name is {0} and I am {1} years old.", name, age);
// String interpolation
string interpolatedString = $"Hello, my name is {name} and I am {age} years old.";
Console.WriteLine(concatString);
Console.WriteLine(formatString);
Console.WriteLine(interpolatedString);
All three approaches produce the same output, but string interpolation is generally more readable and less error-prone, especially with multiple variables.
Using Expressions in String Interpolation
You can include any valid C# expression within the curly braces, not just variables:
int a = 5;
int b = 3;
Console.WriteLine($"The sum of {a} and {b} is {a + b}");
Console.WriteLine($"The product of {a} and {b} is {a * b}");
Console.WriteLine($"Is {a} greater than {b}? {a > b}");
Console.WriteLine($"The lowercase of {"HELLO"} is {"HELLO".ToLower()}");
Output:
The sum of 5 and 3 is 8
The product of 5 and 3 is 15
Is 5 greater than 3? True
The lowercase of HELLO is hello
Formatting Expressions in String Interpolation
String interpolation supports formatting expressions using the same format specifiers used in string.Format()
. The format is specified after a colon inside the curly braces:
double price = 123.456;
DateTime today = DateTime.Now;
// Currency formatting
Console.WriteLine($"The price is {price:C}");
// Number formatting with decimal places
Console.WriteLine($"The value with 2 decimal places: {price:F2}");
// Date formatting
Console.WriteLine($"Today is {today:d}");
Console.WriteLine($"The full date and time: {today:F}");
// Percentage
Console.WriteLine($"Percentage: {0.75:P}");
// Custom numeric format
Console.WriteLine($"Phone number: {5551234567:###-###-####}");
Output (may vary based on your regional settings):
The price is $123.46
The value with 2 decimal places: 123.46
Today is 7/15/2023
The full date and time: Saturday, July 15, 2023 2:30:45 PM
Percentage: 75.00%
Phone number: 555-123-4567
Alignment and Spacing in String Interpolation
You can control the alignment and spacing of interpolated values using the format specifier's alignment component:
string name1 = "John";
string name2 = "Elizabeth";
// Right-align in a 10-character field
Console.WriteLine($"[{name1,10}]");
Console.WriteLine($"[{name2,10}]");
// Left-align in a 10-character field
Console.WriteLine($"[{name1,-10}]");
Console.WriteLine($"[{name2,-10}]");
Output:
[ John]
[Elizabeth]
[John ]
[Elizabeth ]
Combining Alignment and Format Specifiers
You can combine alignment with format specifiers:
double[] values = { 123.456, 78.9, 0.1234 };
Console.WriteLine("Value Table:");
Console.WriteLine("---------------------------------");
Console.WriteLine($"{"Number",-10}{"Currency",12}{"Percent",10}");
Console.WriteLine("---------------------------------");
foreach (double value in values)
{
Console.WriteLine($"{value,-10:F2}{value,12:C}{value,10:P0}");
}
Output:
Value Table:
---------------------------------
Number Currency Percent
---------------------------------
123.46 $123.46 12%
78.90 $78.90 8%
0.12 $0.12 0%
Escaping Braces in String Interpolation
If you need to include curly braces in your interpolated string, you can escape them by doubling them:
int value = 42;
// To display a single { or }, double it
Console.WriteLine($"The value is {{in brackets}}: {value}");
Output:
The value is {in brackets}: 42
Verbatim String Interpolation
You can combine verbatim string literals (prefixed with @
) and string interpolation:
string filePath = "C:\\Program Files\\MyApp";
string fileName = "data.txt";
// Without verbatim string
Console.WriteLine($"File: {filePath}\\{fileName}");
// With verbatim string
Console.WriteLine($@"File: {filePath}\{fileName}");
Output:
File: C:\Program Files\MyApp\data.txt
File: C:\Program Files\MyApp\data.txt
The verbatim string version ($@"..."
) doesn't require double backslashes, making it more readable for file paths.
Real-World Applications
Building a Simple User Profile
string BuildUserProfile(string name, int age, string occupation)
{
return $@"
User Profile
------------------
Name: {name}
Age: {age}
Occupation: {occupation}
Created: {DateTime.Now:yyyy-MM-dd}
------------------";
}
string profile = BuildUserProfile("Alex Johnson", 28, "Software Developer");
Console.WriteLine(profile);
Output:
User Profile
------------------
Name: Alex Johnson
Age: 28
Occupation: Software Developer
Created: 2023-07-15
------------------
Generating HTML Content
string GenerateHtmlCard(string title, string content, string imageUrl)
{
return $@"<div class=""card"">
<img src=""{imageUrl}"" alt=""{title}"">
<div class=""container"">
<h4><b>{title}</b></h4>
<p>{content}</p>
</div>
</div>";
}
string card = GenerateHtmlCard(
"Mountain View",
"Beautiful scenery of mountains at sunset",
"https://example.com/mountains.jpg"
);
Console.WriteLine(card);
Building a SQL Query
string BuildSqlQuery(string tableName, string[] columns, int limit)
{
string columnList = string.Join(", ", columns);
return $"SELECT {columnList} FROM {tableName} LIMIT {limit};";
}
string query = BuildSqlQuery("Users", new[] { "Id", "Name", "Email" }, 10);
Console.WriteLine(query);
Output:
SELECT Id, Name, Email FROM Users LIMIT 10;
Summary
String interpolation in C# provides a clean, readable way to embed expressions within string literals. Key points to remember:
- Prefix the string with
$
to enable interpolation - Place expressions within curly braces
{}
- You can include any valid C# expression inside the braces
- Format specifiers can be added after a colon (e.g.,
{value:C}
) - Alignment can be controlled with comma and a number (e.g.,
{value,10}
) - Combine with verbatim strings (
$@"..."
) for multiline strings without escaping - Double curly braces to escape them (
{{
and}}
)
String interpolation makes your code more readable and maintainable compared to string concatenation or the string.Format()
method, especially when dealing with complex string construction.
Exercises
-
Create a program that asks a user for their name, age, and favorite color, then displays a formatted message using string interpolation.
-
Write a method that takes a decimal price and a quantity, then returns a receipt-like string showing the item price, quantity, and total with proper currency formatting.
-
Create a temperature converter that takes a temperature in Celsius and displays it in both Celsius and Fahrenheit using string interpolation with appropriate formatting.
-
Build a method that generates a simple table of multiplication results for a given number, with proper alignment using string interpolation.
Additional Resources
If you spot any mistakes on this website, please let me know at [email protected]. I’d greatly appreciate your feedback! :)