DEV Community

Juarez Júnior for Develop4Us

Posted on • Edited 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

Qodo Takeover

Introducing Qodo Gen 1.0: Transform Your Workflow with Agentic AI

While many AI coding tools operate as simple command-response systems, Qodo Gen 1.0 represents the next generation: autonomous, multi-step problem-solving agents that work alongside you.

Read full post →

Top comments (0)

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more