How should I concatenate strings?

前端 未结 9 1423
不知归路
不知归路 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:30

    Use the + operator in your scenario.

    I would only use the String.Format() method when you have a mix of variable and static data to hold in your string. For example:

    string result=String.Format(
        "Today {0} scored {1} {2} and {3} points against {4}",..);
    
    //looks nicer than
    string result = "Today " + playerName + " scored " + goalCount + " " + 
        scoreType + " and " + pointCount + " against " + opposingTeam;
    

    I don't see the point of using a StringBuilder, since you're already dealing with three string literals.

    I personally only use Concat when dealing with a String array.

提交回复
热议问题