开发者

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();
// Writ开发者_开发知识库ing
s = "i is " + i;


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.


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"


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.


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜