Boxing and Unboxing in String.Format(...) ... is the following rationalized?
It would be better to avoid the boxing by constructing the string with StringBuilder or StringWriter and using the typed overloads.
Most of the time the boxing should be of little concern and not worth you even being aware of it.
1: yes, as long as the value-type overrides ToString()
, which all the inbuilt types do.
2: because no such behaviour is defined in the spec, and the correct handling of a params object[]
(wrt value-types) is: boxing
string.Format is just like any other opaque method; the fact that it is going to do that is opaque to the compiler. It would also be functionally incorrect if the pattern included a format like {0:n2}
(which requires a specific transformation, not just ToString()
). Trying to understand the pattern is undesirable and unreliable since the pattern may not be known until runtime.
The compiler doesn't do this for you because string.Format
takes a params Object[]
. The boxing happens because of the conversion to Object
.
I don't think the compiler tends to special case methods, so it won't remove boxing in cases like this.
Yes in many cases it is true that the compiler won't do boxing if you call ToString()
first. If it uses the implementation from Object
I think it would still have to box.
Ultimately the string.Format
parsing of the format string itself is going to be much slower than any boxing operation, so the overhead is negligible.