Search code examples
c#stringstring-concatenation

Building up strings from variables by neither using + nor StringBuilder


Assume we have

string one = "1";
string two = "2";
string three = "3";

And we want to get the result string

result = "1, 2, 3"

by building it from the above three variables.

I know I can do it like this

result = one + ", " + two + ", " + three;

but as far as I understand, then a lot of strings are generated and thrown away again (first 1, then 1,, then 1, 2, then 1, 2,, then 1, 2, 3). I know I can use a StringBuilder to prevent creating new strings all the time, but this is also not what I am looking for.

In my case, I know from the start how the string will look, I only need to put references of the variables into the result string.

I know I have seen a syntax before (C#). I think it looks a bit like this:

result = "{0}, {1}, {2}", one, two, three

Questions:

  • What is the syntax?

  • What is the correct name for putting a string together from pieces when the pattern is known? I assume there is a more specific word than "concatenate". In my understanding, "concatenate" is something you want to do at runtime, when you don't know in the beginning which or how many strings are to be connected.

- Is there a difference in performance or memory usage compared to using a StringBuilder? (see https://stackoverflow.com/a/299541/5333340 - it seems string.Concat is faster.)


Solution

    • What is the syntax?

    var result = string.Format("{0}, {1}, {2}", one, two, three);

    or (C# 6.0 string interpolation, which is just syntactic sugar for string.Format)

    var result = $"{one}, {two}, {three}";

    • What is the correct name for putting a string together from pieces when the pattern is known? I assume there is a more specific word than "concatenate". In my understanding, "concatenate" is something you want to do at runtime, when you don't know in the beginning which or how many strings are to be connected.

    String formatting or string interpolation.

    • Is there a difference in performance or memory usage compared to using a StringBuilder?

    As of .NET 4.0, string.Format uses a cached StringBuilder internally, so the performance difference is minimal. For very large and/or very many strings, using a raw StringBuilder will be fastest, but for most cases, string.Format will be good enough in terms of performance, and a lot more readable.