Reputation: 51084
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 +
...
Upvotes: 11
Views: 4241
Reputation: 59021
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.
Upvotes: 20
Reputation: 4685
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.
Upvotes: 8
Reputation: 14286
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.
Upvotes: 1
Reputation: 3695
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.
Upvotes: 2