DEV Community

Juarez Júnior
Juarez Júnior

Posted on

C# Tip: Prefer String Interpolation over Concatenation

Let’s talk about the practice of Preferring String Interpolation over Concatenation, which makes code more readable and efficient when working with strings in C#.

Explanation:

In C#, string interpolation (using $"text {variable}") is generally clearer and more efficient than concatenation ("text " + variable). Interpolation allows you to insert variables directly within strings, improving readability and avoiding excessive use of concatenation operators. Performance-wise, interpolation is optimized by the compiler and creates fewer temporary objects, reducing memory usage compared to concatenation, especially with large strings or multiple concatenations.

This practice is useful in scenarios that involve creating messages, logs, or any other situation where dynamic strings are needed.

Code:

public class Program
{
    public static void Main()
    {
        string name = "John";
        int age = 30;

        // Using interpolation instead of concatenation
        string message = $"Name: {name}, Age: {age}";

        Console.WriteLine(message);
    }
}
Enter fullscreen mode Exit fullscreen mode

Code Explanation:

In the example, we use string interpolation to combine text and variables in a more readable and efficient way. This improves code clarity and eliminates the need for multiple concatenation operations.

String Interpolation in C# is a more readable and efficient way to work with strings, especially in scenarios where multiple variables need to be inserted. It improves code clarity and reduces memory usage, particularly in extensive concatenations.

I hope this tip helps you prefer string interpolation to enhance readability and efficiency in your code! Until next time.

Source code: GitHub

Top comments (0)