Jamie Kitson Jamie Kitson - 9 months ago 52
C# Question

String.Format parameter order annoyance

it's really annoying how C# seems to force you to explicitly name the index of every parameter in String.Format, if you want to add another parameter somewhere you either have to re-index the string or put your new parameter at the end.

Is there a way to get C# to do this automatically?

e.g. (I know this is pointless pedants, it's just an example :)

I start with:

String.Format("{0} {1} {1} {2} {3}", a, b, c, d)

if I want to add a parameter at the beginning I can do one of the following:

String.Format("{4} {0} {1} {1} {2} {3}", a, b, c, d, e)
String.Format("{0} {1} {2} {2} {3} {4}", e, a, b, c, d)

in Delphi for example I could do the equivalent of this:

String.Format("{} {} {} {2} {} {}", e, a, b, c, d)

Answer Source

Well, there's nothing in C# to do this automatically for you. You could always write your own method to do it, but frankly I'd find it less readable. There's a lot more thinking to do (IMO) to understand what your final line does than the previous one. When you hit the {2} you've got to mentally backtrack and replace the previous item with {3} to skip the {2} etc.

Personally I prefer code which takes a bit longer to type, but is clear to read.