C# tutorials > Modern C# Features > C# 6.0 and Later > What is string interpolation and how do you use it?
What is string interpolation and how do you use it?
String interpolation is a feature introduced in C# 6.0 that allows you to embed C# expressions directly within string literals. It provides a more readable and convenient way to format strings compared to older methods like Instead of using placeholders and arguments, you can directly insert variables and expressions inside a string by prefixing the string with a string.Format
or string concatenation.$
and enclosing the expressions in curly braces {}
.
Basic String Interpolation
This is the simplest form of string interpolation. We define a string prefixed with $
and embed the variables name
and age
within curly braces. The C# compiler automatically evaluates these expressions and inserts their values into the string at runtime.
string name = "Alice";
int age = 30;
string message = $"Hello, my name is {name} and I am {age} years old.";
Console.WriteLine(message); // Output: Hello, my name is Alice and I am 30 years old.
Formatting with Interpolation
String interpolation allows you to use standard .NET formatting strings within the curly braces. In this example, :C2
formats the price
variable as currency with two decimal places.
double price = 123.4567;
string formattedPrice = $"The price is {price:C2}.";
Console.WriteLine(formattedPrice); // Output: The price is $123.46.
Using Expressions in Interpolation
You can embed complex expressions directly within the interpolated string. Here, we're calculating the sum of x
and y
directly within the string.
int x = 5;
int y = 10;
string result = $"The sum of {x} and {y} is {x + y}.";
Console.WriteLine(result); // Output: The sum of 5 and 10 is 15.
Verbatim String Literals and Interpolation
You can combine verbatim string literals (prefixed with @
) with string interpolation. This is especially useful when dealing with file paths or other strings containing backslashes.
string filePath = @"C:\MyFolder\MyFile.txt";
string message = $"The file path is: {filePath}";
Console.WriteLine(message); // Output: The file path is: C:\MyFolder\MyFile.txt
Concepts behind the snippet
String interpolation is syntactic sugar provided by the C# compiler. Behind the scenes, the compiler transforms interpolated strings into calls to string.Format
or string.Concat
depending on the complexity of the interpolation. This transformation is done at compile time, so there is no runtime performance penalty compared to using string.Format
directly.
Real-Life Use Case
Imagine building a dynamic query builder for a database. String interpolation makes it easy to construct SQL queries based on user input: This allows you to assemble the query dynamically based on your variables.string tableName = "Customers";
string columnName = "Name";
string searchTerm = "John";
string query = $"SELECT * FROM {tableName} WHERE {columnName} = '{searchTerm}'";
Best Practices
CultureInfo
to format numbers and dates correctly for different locales.
Interview Tip
Be prepared to discuss the benefits of string interpolation over older methods like string.Format
, focusing on readability, conciseness, and reduced risk of errors. Also, be aware of the potential for injection vulnerabilities when using string interpolation with user input.
When to use them
String interpolation should be used whenever you need to create a string that incorporates the values of variables or the results of expressions. It is a preferred method over concatenation and string.Format
because it is generally more readable and less prone to errors.
Memory footprint
String interpolation, under the hood, leverages string.Format
or string.Concat
. Therefore, the memory footprint is generally comparable to using those methods directly. String operations in C# always create new string objects since strings are immutable. Be mindful of excessive string creation in performance-critical sections of your code.
Alternatives
While string interpolation is generally preferred, the alternatives are:
+
operator to combine strings. Less readable and can be less efficient for many concatenations.string.Format
: Still a viable option, especially when dealing with older codebases. Can be less readable than string interpolation.StringBuilder
: More efficient for building strings with many concatenations, particularly within loops.
Pros
string.Format
.
Cons
StringBuilder
for large-scale string manipulation.
FAQ
-
Is string interpolation faster than string.Format?
Generally, the performance difference between string interpolation andstring.Format
is negligible. The compiler often optimizes string interpolation intostring.Format
calls. Focus on readability and maintainability rather than micro-optimizations in this case. -
Can I use string interpolation in older versions of C#?
No, string interpolation was introduced in C# 6.0. If you're using an older version, you'll need to usestring.Format
or string concatenation. -
How do I escape curly braces in an interpolated string?
To escape curly braces, you need to double them. For example, to include '{' in the string, use '{{'.