views:

187

answers:

3

Is there a way to tell the String.Format() function (without writing my own function) how many placeholders there are dynamically? It we be great to say 15, and know I'd have {0}-{14} generated for me. I'm generate text files and I often have more than 25 columns. It would greatly help.

OK,

I will rephrase my question. I wanted to know if it is at all possible to tell the String.Format function at execution time how many place-holders I want in my format string without typing them all out by hand.

I'm guessing by the responses so far, I will just go ahead and write my own method.

Thanks!

+1  A: 

Adding a bit to AlbertEin's response, I don't believe String.Format can do this for you out-of-the-box. You'll need to dynamically create the format string prior to using the String.Format method, as in:

var builder = new StringBuilder();

for(var i = 0; i < n; ++i)
{
  builder.AppendFormat("{0}", "{" + i + "}");
}

String.Format(builder.ToString(), ...);

This isn't exactly readable, though.

David Andres
Thanks for the start, I had begun a similar routine. I guess I should get more sleep before asking something so obvious ;)
Chris
@Chris - No prob. If the code block you're formatting is any longer than what is shown here please comment accordingly. This isn't an approach I see often and may confuse many.
David Andres
+1  A: 

Why use string.Format when there is no formatting (atleast from what I can see in your question)? You could use simple concatenation using stringbuilder instead.

shahkalpesh
A: 

There is a way to do this directly:

Just create a custom IFormatProvider, then use this overload of string.Format.

For example, if you want to always have 12 decimal points, you can do:

CultureInfo culture = Thread.CurrentThread.CurrentCulture.Clone(); // Copy your current culture
NumberFormatInfo nfi = culture.NumberFormat;
nfi.NumberDecimalDigits = 12; // Set to 12 decimal points

string newResult = string.Format(culture, "{0}", myDouble); // Will put it in with 12 decimal points
Reed Copsey