C# tutorials > Core C# Fundamentals > Basics and Syntax > How do you use string interpolation?

How do you use string interpolation?

String interpolation is a powerful feature in C# that allows you to embed variables directly into string literals, making your code more readable and maintainable. It provides a concise way to format strings by replacing placeholders with variable values. This tutorial covers the fundamentals of string interpolation, explores its practical applications, and offers best practices for utilizing it effectively.

Basic Syntax

String interpolation uses the $ symbol before the string literal. Inside the string, you can embed variables or expressions within curly braces {}. The values of these variables/expressions are then inserted into the string at runtime. The $ symbol tells the compiler to treat the string as an interpolated string.

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.

Concepts Behind the Snippet

Behind the scenes, string interpolation utilizes the string.Format() method. The compiler transforms the interpolated string into a string.Format() call, optimizing the string construction process. This makes interpolation not only more readable but also generally more efficient than traditional string concatenation (using the + operator), especially when dealing with multiple variables.

Real-Life Use Case: Logging

String interpolation is highly useful for logging. It provides a clean way to include dynamic information (like usernames, timestamps, or status codes) in log messages, making debugging and monitoring significantly easier. The example demonstrates how to format the DateTime object within the interpolated string using format specifiers (yyyy-MM-dd HH:mm:ss).

string username = "Bob123";
DateTime loginTime = DateTime.Now;

// Logging the user login information
Console.WriteLine($"User {username} logged in at {loginTime:yyyy-MM-dd HH:mm:ss}.");

Real-Life Use Case: Database Queries

While possible to use string interpolation to create database queries, be extremely careful with SQL injection vulnerabilities. Never directly embed user-provided input into SQL queries using string interpolation without proper sanitization and parameterization. Parameterization is a much safer and preferred approach. The above example is for demonstrating interpolation only and should NOT be used in production without thorough security review and mitigation.

//Example demonstrating the use of string interpolation with sql queries, be careful with SQL injection!
string tableName = "Customers";
string columnName = "Name";
string sqlQuery = $"SELECT {columnName} FROM {tableName} WHERE Id = 1;";

Console.WriteLine(sqlQuery);

Format Specifiers

String interpolation allows you to use format specifiers within the curly braces to control how values are displayed. In the example, :C2 formats the price variable as currency with two decimal places. Other common format specifiers include date and time formatting (:yyyy-MM-dd), number formatting (:N2 for numbers with two decimal places and commas), and hexadecimal formatting (:X).

double price = 123.456;
string formattedPrice = $"The price is {price:C2}."; // C2 formats as currency with 2 decimal places
Console.WriteLine(formattedPrice); // Output: The price is $123.46 (or your local currency)

Best Practices

  • Use with Readability in Mind: Prioritize readability when using string interpolation. Break up complex expressions into separate variables to improve clarity.
  • Avoid Excessive Complexity: While you can embed complex expressions, keep them simple within the interpolation. For more complex logic, calculate the result separately and then embed the variable.
  • Escape Curly Braces: If you need to include literal curly braces in your string, escape them by using double curly braces: {{ and }}. For example: string message = $"This is a literal brace: {{}}";

Interview Tip

Be prepared to discuss the advantages of string interpolation over older methods like string.Format() and string concatenation. Highlight its readability, conciseness, and generally better performance (especially compared to repeated string concatenation with the + operator). Also, understand the security implications when using interpolation with external data, particularly in contexts like database queries or command execution.

When to Use String Interpolation

String interpolation is ideal for scenarios where you need to create dynamic strings from variables. Consider using it for:

  • Creating user-friendly messages
  • Generating reports
  • Formatting data for display
  • Constructing log messages
Avoid string interpolation when building very large strings in a loop, as repeated string creation can impact performance. In such cases, consider using a StringBuilder.

Memory Footprint

Like all strings in C#, interpolated strings are immutable. Each time you modify a string, a new string object is created in memory. While string interpolation is generally efficient, creating and discarding many strings in a loop can lead to memory fragmentation and performance issues. For repeated string manipulation, use a StringBuilder to minimize memory allocation and improve efficiency.

Alternatives to String Interpolation

While string interpolation is often the preferred method, alternatives include:

  • string.Format(): This is the traditional way to format strings. It uses numbered placeholders (e.g., {0}, {1}). It's still useful in older codebases or when you need to align with existing coding standards.
  • String Concatenation (+ operator): While simple, it's less efficient than interpolation, especially with multiple variables. It can also be less readable.
  • StringBuilder: Ideal for building strings incrementally, especially in loops, to avoid the overhead of creating multiple string objects.

Pros of String Interpolation

  • Readability: Easier to read and understand compared to string concatenation or string.Format().
  • Conciseness: Requires less code to achieve the same result.
  • Performance: Generally more efficient than string concatenation, especially with multiple variables.
  • Inline Expressions: Allows embedding expressions directly within the string.
  • Format Specifiers: Supports using format specifiers for precise control over value formatting.

Cons of String Interpolation

  • Potential for SQL Injection: When used improperly with user-provided data in database queries. Requires careful sanitization and parameterization.
  • Immutability: String are immutable which may have performance implication in loops.
  • Limited Control in Some Scenarios: For highly complex formatting requirements, string.Format() might offer more fine-grained control.

FAQ

  • Can I use string interpolation with custom objects?

    Yes, you can use string interpolation with custom objects. The ToString() method of the object will be called to get its string representation. You can override the ToString() method in your custom class to provide a meaningful string representation for interpolation.
  • Is string interpolation available in all C# versions?

    String interpolation was introduced in C# 6.0. If you are using an older version of C#, you will need to use string.Format() or string concatenation instead.
  • How can I include a literal dollar sign ($) in an interpolated string?

    To include a literal dollar sign in an interpolated string, you need to escape it by using two dollar signs: $$. For example: string price = "100"; string message = $"The price is $${price}."; Console.WriteLine(message); // Output: The price is $100.