C# > Language Features by Version > C# 6 to C# 12 Highlights > String Interpolation (C# 6)

String Interpolation in C# 6: A Concise Guide

C# 6 introduced string interpolation, a feature that significantly simplifies string formatting. Instead of using `string.Format()` or string concatenation, you can embed expressions directly within string literals using the `$` symbol. This leads to cleaner, more readable, and less error-prone code.

Basic String Interpolation

This example demonstrates the fundamental usage of string interpolation. The `$` prefix before the string literal enables interpolation. Variables `name` and `age` are directly embedded within the string using curly braces `{}`. The values of these variables are then inserted 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 also supports formatting specifiers, similar to `string.Format()`. The format specifier (e.g., `C2` for currency with two decimal places, `D` for the long date format) is placed after the expression, separated by a colon within the curly braces. This allows for precise control over how values are displayed within the interpolated string.

double price = 123.4567;
string formattedPrice = $"The price is {price:C2}.";
Console.WriteLine(formattedPrice); // Output: The price is $123.46 (assuming US culture)

DateTime now = DateTime.Now;
string formattedDate = $"Today is {now:D}.";
Console.WriteLine(formattedDate); // Output: Today is Wednesday, October 26, 2023 (example)

Arbitrary Expressions within Interpolation

String interpolation isn't limited to just variable names. You can embed more complex expressions directly within the curly braces. In the first example, the sum of `x` and `y` is calculated and inserted into the string. The second example demonstrates the use of the ternary operator within an interpolated string for conditional logic.

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.

string greeting = $"Hello, {(name == null ? "Guest" : name)}!";
Console.WriteLine(greeting); //If name is not null output: Hello, Alice!

Concepts Behind the Snippet

The key concept is compile-time parsing and efficient string creation. The C# compiler analyzes the interpolated string and generates optimized code to build the final string. This is typically more efficient than repeated string concatenation. The expression within the curly braces is evaluated at runtime and converted to a string representation.

Real-Life Use Case Section

String interpolation is perfect for generating dynamic messages, constructing SQL queries (use with caution to avoid SQL injection!), creating file paths, and displaying formatted data in user interfaces. It's a versatile tool that simplifies many common programming tasks.

// Example: Constructing a file path
string fileName = "report.txt";
string directory = "/data/reports";
string fullPath = $"{directory}/{fileName}";
Console.WriteLine(fullPath);

Best Practices

  • Use string interpolation whenever you need to format strings dynamically.
  • Keep expressions within the curly braces simple and readable. For complex logic, pre-calculate the result and store it in a variable before using it in the interpolated string.
  • Be mindful of culture-specific formatting. Use `CultureInfo` to ensure correct formatting for different regions.
  • Sanitize user input when constructing strings that will be used in SQL queries or file paths to prevent security vulnerabilities.

Interview Tip

Be prepared to discuss the advantages of string interpolation over `string.Format()` and string concatenation. Highlight the improved readability, reduced verbosity, and potential performance benefits. Also, understand how to format data within interpolated strings.

When to Use Them

Use string interpolation whenever you need to combine string literals with variables or expressions. It's especially useful when you need to format data in a specific way (e.g., currency, dates, numbers).

Memory Footprint

String interpolation typically has a similar memory footprint to `string.Format()`. The compiler optimizes the process to create a new string efficiently. Avoid excessive string manipulation within the interpolation expression to minimize memory allocation.

Alternatives

  • `string.Format()`: A traditional method for string formatting that is still valid but less readable than interpolation.
  • String concatenation using the `+` operator: Less efficient and less readable than interpolation, especially for complex formatting.
  • StringBuilder: More efficient for building strings in loops or when performing a large number of string manipulations, but requires more verbose code.

Pros

  • Improved readability and conciseness compared to `string.Format()` and string concatenation.
  • Reduced verbosity, leading to cleaner code.
  • Potentially better performance than string concatenation.
  • Direct embedding of expressions within strings.

Cons

  • Requires C# 6 or later.
  • Can become less readable if the expressions within the curly braces are too complex.
  • Requires careful handling of user input to prevent security vulnerabilities.

FAQ

  • What is string interpolation?

    String interpolation is a C# 6 feature that allows you to embed expressions directly within string literals, making string formatting more readable and concise.
  • How does string interpolation differ from `string.Format()`?

    String interpolation is generally more readable and concise than `string.Format()`. It allows you to directly embed variables and expressions within the string, whereas `string.Format()` requires you to use numbered placeholders.
  • Can I use formatting specifiers with string interpolation?

    Yes, you can use formatting specifiers with string interpolation by placing them after the expression, separated by a colon within the curly braces (e.g., `{price:C2}`).
  • Does String Interpolation prevent against SQL injection?

    No, String Interpolation does not automatically prevent SQL injection. You must still sanitize any user input before using it in a SQL query, regardless of whether you are using String Interpolation or another method of constructing the query string.