Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Redundant Call to Object.ToString()

Tags:

c#

.net

resharper

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 + ...

like image 622
ProfK Avatar asked Sep 16 '08 16:09

ProfK


Video Answer


2 Answers

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.

like image 193
Haacked Avatar answered Oct 02 '22 23:10

Haacked


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.

like image 42
Thomas Danecker Avatar answered Oct 02 '22 21:10

Thomas Danecker