In most code that I come across, they explicitly convert an int or other number to a string while using String.Format(), although from what I’ve noticed it is not necessary. Is there something I’m missing which requires explicit conversion of a number to a string before using it as a string?
Explicit:
int i = 13;
string example = String.Format("If a Friday lands on the {0}th of the month, it is generally considered to be an unlucky day!",
i.ToString());
Which produces example as: "If a Friday lands on the 13th of the month, it is generally considered to be an unlucky day!"
Non-explicit:
int i = 13;
string example = String.Format("If a Friday lands on the {0}th of the month, it is generally considered to be an unlucky day!",
i);
Which produces example as: "If a Friday lands on the 13th of the month, it is generally considered to be an unlucky day!" (the same as explicitly converting). So why do the majority of coders I see do this?
If you use an implicit conversion, the
intis boxed toobjectfirst. That’s a tiny performance hit, but one which some people seem to think is important, and may explain the code.Indeed, Jeffrey Richter wrote about this (encouraging the use of this sort of thing) in his otherwise-excellent CLR via C#. It irritated me enough that I blogged about it 🙂
Of course in some places, boxing may be relevant – but given that
string.Formatneeds to walk the format string and do all kinds of other things, I wouldn’t expect it to be significant here… and that’s before you consider what you’re going to do with the string next 🙂