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?

+3


source to share


3 answers


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 :)

+7


source


I really don't see a reason for this. Since String.Format()

it does it already as you point out, it is more compact and IMO easier to read if you just let it be String.Format()

taken care of.



0


source


Because we are used to the rules and you better be too. String.Format()

is a smart method, every method is not. remember what String.Format()

accepts objects, so you don't need to convert, however if you are sending an object anyway.

0


source







All Articles