Xaqron
Xaqron

Reputation: 30857

Using '.ToString()' with numeric variables

Is there any drawback for omitting .ToString() while converting numeric values to string ?

int i = 1234;
string s;
// Instead of
s = "i is " + i.ToString();
// Writing
s = "i is " + i;

Upvotes: 2

Views: 263

Answers (4)

Michael Stum
Michael Stum

Reputation: 180944

It doesn't make a difference in this case.

"Count: " + i

compiles down to

String.Concat("Count: ",i)

String.Concat has multiple overloads, and I believe that the Concat(Object, Object) overload is chosen (since the only common ancestor of string and int is object).

The internal implementation is this:

 return (arg0.ToString() + arg1.ToString());

If you call

"Count: " + i.ToString()

then it chooses the Concat(String, String) overload since both are strings.

So for all practical matters, it's essentially doing the same anyway - it's implicitly calling i.ToString().

I usually omit .ToString in cases like the above because it just adds noise.

Upvotes: 4

svick
svick

Reputation: 244777

The only drawback I can think of is that you can put additional parameters to ToString().

But in most cases where you could concatenate string with an int, I think the better solution is to use string.Format():

string.Format("i is {0}", i);

In your case, it's not as obvious that this way is better, but you start thinking about adding proper punctuation (i is {0}.), changing the output slightly in some other way, or supporting localization, the advantages of this way become clear.

Upvotes: 1

Mario
Mario

Reputation: 36487

Despite the fact it won't compile (at least it won't using Visual Studio 2008 without adding another "" in front of the first i) there ARE differences, depending on how you use it (assuming it would work) and in which order operators are handled (in C# and I guess almost all languages + has a higher priority than =):

int i = 1234;
string s;
s = i.ToString(); // "1234"
s = i.ToString() + i.ToString(); // "12341234"
s = i; // "1234"
s = i + i; // "2468" (but only if you don't add "" in front)

Edit: With the updated code there's no real difference assuming you don't use brackets to group several non-string objects/variables:

int i = 1234;
string s;
s = "" + i + i; // "12341234"
s = "" + (i + i); // "2468"

Upvotes: 1

Ryan
Ryan

Reputation: 1382

The assignment s = i will not compile when Option Strict is on (default for C#).

Upvotes: 0

Related Questions