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 string.Format or string concatenation.

Instead of using placeholders and arguments, you can directly insert variables and expressions inside a string by prefixing the string with a $ 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:

string tableName = "Customers"; string columnName = "Name"; string searchTerm = "John"; string query = $"SELECT * FROM {tableName} WHERE {columnName} = '{searchTerm}'";

This allows you to assemble the query dynamically based on your variables.

Best Practices

  • Avoid complex logic within interpolation expressions. Keep the expressions simple for readability. If you need complex calculations, perform them beforehand and store the result in a variable.
  • Be mindful of culture-specific formatting. Use CultureInfo to format numbers and dates correctly for different locales.
  • Sanitize user input. When using string interpolation with user input (e.g., in SQL queries), always sanitize the input to prevent injection vulnerabilities.

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:

  • String Concatenation: Using the + 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

  • Readability: Significantly improves code readability compared to string concatenation and string.Format.
  • Conciseness: Reduces the amount of code needed to create formatted strings.
  • Reduced Errors: Less prone to errors due to incorrect argument order or placeholder mismatches.

Cons

  • Security Risks: Can introduce security vulnerabilities if used with unsanitized user input (e.g., SQL injection).
  • Performance: While generally performant, excessive string creation can still impact performance. Use StringBuilder for large-scale string manipulation.

FAQ

  • Is string interpolation faster than string.Format?

    Generally, the performance difference between string interpolation and string.Format is negligible. The compiler often optimizes string interpolation into string.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 use string.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 '{{'.