Assigning String.Empty plus some string to a button text
I stumbled up开发者_如何学JAVAon this code and I am curious as to what use may the string.Empty
part have in it. Is it as completely useless as it seems? Am I missing something?
System.Windows.Forms.ToolStripButton m_button;
int errorCount;
...
m_button.Text = string.Empty + errorCount + " error(s)";
It looks like it's to allow errorCount
to be implicitly cast to string
rather than having to do an explicit cast - i.e. errorCount.ToString()
. However, as you point out, the implicit cast is perfectly valid, so it must be the result of some code review, old code being changed, or StyleCop type code "cleaner" being run.
It's bad programming really.
A better solution might be to do:
m_button.Text = string.Format("{0} error(s)", errorCount);
There's no reason to use it. Presumably the original coder thought that it was necessary to prevent the compiler from trying to add a string to an int, but the compiler automatically turns the int into a string making it superfluous.
So yes, it is completely useless.
you're right, it's absolutely useless. the integer will be converted to string anyway because of the + " error(s)". maybe it wasn't here first.
Because it will use the addition operator belonging to the string class. Since errorCount
is an integer, adding a string to it is somewhat awkward. This is why explicit string to which an int
is first added is more straightforward and will convert the int
to a string
.
精彩评论