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
Option 3 doesn’t compile cause you cannot cast an
inttostring.The two others produce the same result. However, there’s a subtle difference.
Internally the plus operator compiles to a call to
String.Concat.Concathas different overloads. Option 1 callsConcat(string, string, string)while option 2 callsConcat(object, object, object)with two strings and a boxed int. InternallyConcatthen callsToStringon the boxed int.Also, check this related question: Strings and ints, implicit and explicit