Are there differences between these examples? Which should I use in which case?
var str1 = "abc" + dynamicString + dynamicString2;
var str2 = String.Format("abc{0}{1}", dynamicString, dynamicString2);
var str3 = new StringBuilder("abc").
Append(dynamicString).
Append(dynamicString2).
ToString();
var str4 = String.Concat("abc", dynamicString, dynamicString2);
There are similar questions:
- Difference in String concatenation which only asks about the
+operator, and it’s not even mentioned in the answer that it is converted to String.Concat - What’s the best string concatenation method which is not really related to my question, where it is asking for the best, and not a comparation of the possible ways to concatenate a string and their outputs, as this question does.
This question is asking about what happens in each case, what will be the real output of those examples? What are the differences about them? Where should I use them in which case?
Gathering information from all the answers it turns out to behave like this:
The
+operator is the same as theString.Concat, this could be used on small concatenations outside a loop, can be used on small tasks.In compilation time, the
+operator generate a single string if they are static, while theString.Concatgenerates the expressionstr = str1 + str2;even if they are static.String.Formatis the same asStringBuilder..(example 3) except that theString.Formatdoes a validation of params and instantiate the internalStringBuilderwith the length of the parameters.String.Formatshould be used when format string is needed, and to concat simple strings.StringBuildershould be used when you need to concatenate big strings or in a loop.