tags:

views:

435

answers:

5

I have a function that takes, amongst others, a parameter declared as int privateCount. When I want to call ToString() on this param, ReSharper greys it out and marks it as a redundant call. So, curious as I am, I remove the ToString(), and the code still builds!

How can a C# compiler allow this, where str is a string?

str += privateCount + ...

+10  A: 

The + operator for string is overloaded to call String.Concat passing in the left and right side of the expression. Thus:

string x = "123" + 45;

Gets compiled to:

String.Concat("123", 45);

Since String.Concat takes in two objects, the right hand side (45) is boxed and then ToString() is called on it.

Note that this "overloading" is not via operator overloading in the language (aka it's not a method named op_Addition) but is handled by the compiler.

Haacked
A: 

To the point answer by Haacked. I dont even need to add anything to it.

Mostlyharmless
+2  A: 

C# automatically converts the objects to strings for you. Consider this line of code:

aString = aString + 23;

This is valid C#; it compiles down to a call to String.Concat(), which takes two objects as arguments. Those objects are automatically converted to string objects for you.

The same thing occurs when you write:

aString += 23;

Again, this compiles down to the same call to String.Concat(); it's just written differently.

Stephen Deken
A: 

This is a valid bad practice, as you must think twice if the variable is a string or an int. What if the variable would be called myInt?

myInt = myInt + 23;

it is more readable and understandable in this form?

myInt = mInt + "23";

or even:

myInt = string.Format("{0}{1}", myInt, 23);

We know from the code that it is a string and not an integer.

Drejc
+1  A: 

It is not only bad practice, but also less performant: The integer has to be boxed because String.Concat expectes an object while int.ToString() does not require boxing.

Thomas Danecker
Did you measure the performance difference actually?
Ilya Ryzhenkov
Jeffrey Richter wrote about it in his famous book "CLR via C#" (page 135f).
Thomas Danecker