What is the reason for explicitly converting int to String.Format ()
Most of the codes I come across explicitly convert an int or other number to a string when using String.Format (), although from what I've noticed this is not necessary. Is there something I'm missing that requires an explicit number-to-string conversion 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());
Creates 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);
Creates example
as: "If a Friday lands on the 13th of the month, it is generally considered to be an unlucky day!"
(same as explicit conversion). So why are most of the coders I see doing this?
source to share
If you are using implicit conversion, it int
is put into the field first object
. This is a tiny performance hit, but one that some people seem to think is very important and can explain the code.
Indeed, Jeffrey Richter wrote about this (encouraging the use of this sort of thing) in his excellent excellent CLR via C #. It annoyed me so much that I blogged about it :)
Of course boxing might be appropriate in some places, but assuming one has string.Format
to go through the format string and do all sorts of other things, I wouldn't expect it to be significant here ... and that before you consider what you're going to do with the next line :)
source to share