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 (see https://stackoverflow.com/a/299541/5333340 - it seems StringBuilder
?string.Concat
is faster.)