How should I concatenate strings?

前端 未结 9 1438
不知归路
不知归路 2020-12-06 00:43

Are there differences between these examples? Which should I use in which case?

var str1 = \"abc\" + dynamicString + dynamicString2;

var str2 = String.Form         


        
9条回答
  •  生来不讨喜
    2020-12-06 01:20

    Gathering information from all the answers it turns out to behave like this:

    The + operator is the same as the String.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 the String.Concat generates the expression str = str1 + str2; even if they are static.

    String.Format is the same as StringBuilder.. (example 3) except that the String.Format does a validation of params and instantiate the internal StringBuilder with the length of the parameters.

    String.Format should be used when format string is needed, and to concat simple strings.

    StringBuilder should be used when you need to concatenate big strings or in a loop.

提交回复
热议问题