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 +
...
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With