views:

82

answers:

4

I stumbled upon 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)";
+9  A: 

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);
ChrisF
What's interesting is that m_button.Text = errorCount + " error(s)"; does compile without a warning anyway.
Daniel Daranas
@Daniel - it might be that the writer was using StyleCop or ReSharper or some other code "cleaner" that objected to the original line. However, that's pure speculation on my part.
ChrisF
@ChrisF - true, StyleCop may have had an influence in this. FWIF I finally changed the code to m_button.Text = string.Format(CultureInfo.CurrentCulture, "{0} error(s)", errorCount);.StyleCop complains if I use the version without CurrentCulture.
Daniel Daranas
Apologies to whoever's edits I just overwrote. I got the "post edited" warning just as I hit the "update" button
ChrisF
+1  A: 

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.

Kerido
+3  A: 

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.

Gabe
+2  A: 

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.

remi bourgarel