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
a source to share
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
a source to share