tags:

views:

112

answers:

3

Which of these 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 is for str to evaluate to: HELLO23WORLD

+6  A: 
int X = 23;
string str = string.Format("HELLO{0}WORLD", X);
Darin Dimitrov
Please leave a comment when down-voting. Is there something wrong with my answer?
Darin Dimitrov
-1: the question asked which of the three code segments produced a correct result, but your answer is still useful because it shows an alternative method, but it is not answering the question
Craig Johnston
+1: **much** better than concatenating strings. It feels wrong that the answerer got penalized simply because he did not explain why it is a better option than the 3 posted in the question.
ANeves
The question asked which of the three was correct. Creating a fourth option is not a valid answer to the question.
Craig Johnston
+4  A: 

Option 3 doesn't compile cause you cannot cast an int to string.

The two others produce the same result. However, there's a subtle difference.

Internally the plus operator compiles to a call to 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 boxed int. Internally Concat then calls ToString on the boxed int.

Also, check this related question: http://stackoverflow.com/questions/517695/strings-and-ints-implicit-and-explicit

Brian Rasmussen
Why doesn't option 2 call ToString() on the int and use the Concat(string, string, string) overload?
Craig Johnston
I would assume that it is because it makes code generation for the caller simpler by letting the Concat method do all the work.
Brian Rasmussen
+1  A: 

you can use StringBuilder too:

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