C #: how to build strings

Which one will achieve the correct result:

(1)

int X = 23;
string str = "HELLO" + X.ToString() + "WORLD";

      

(2)

int X = 23;
string str = "HELLO" + X + "WORLD";

      

(3)

int X = 23;
string str = "HELLO" + (string)X + "WORLD";

      

EDIT: The "correct" result str

for the evaluation is: HELLO23WORLD

+2


a source to share


3 answers


Option 3 doesn't compile because you can't cast int

before string

.

The other two produce the same result. However, there is a subtle difference.



The inner plus statement is compiled to be called String.Concat

. Concat

has different overloads. Option 1 calls Concat(string, string, string)

, while option 2 calls Concat(object, object, object)

with two strings and a nested int. Internally Concat

then calls ToString

on the inserted int.

Also check this related question: Strings and ints, implicit and explicit

+4


a source


int X = 23;
string str = string.Format("HELLO{0}WORLD", X);

      



+7


a source


you can also use StringBuilder:

System.Text.StringBuilder str = new System.Text.StringBuilder();
str.Append("HELLO"); 
str.Append(X); 
str.Append("World");

      

+1


a source







All Articles