Wednesday, December 5, 2007

String.Format - include { in output

I had to work with string formatting today for a number of time.
string.Format is a powerful mechanism to display strings in different format. It formats numeric values, date values and many other objects into different formats, different patterns.

I had to format a number based on the format given from the configuration file. It is just a simple case of left padding with zeros. The value in the configuration file will be like "######". Based on the length of this mask, I have to pad the resultant number. For example, if the mask is "######" and the number is 6, I should display the result as "000006".

It is a simple issue, if I use string concatenation connected to string.Format. So first I did the same in the following way.

string format = "{0:d" + mask.Length.ToString() + "}";
string formattedValue = string.Format(format, count);

But I felt that this is wrong. I don't use string concatenation. A performance issue. I have to use string.Format for the total formatting. So I tried many ways to format; but most of them resulted into run time error. For example,

string format = string.Format("{0:d{0}}", mask.Length);
string formattedValue = string.Format(format, count);

I understood that this happens because there I need "{" in the output of the first line. An escape sequence? I tried to put a "\" just before the "{". Now even the compiler didn't allow me to do so.

So what is next? After a moment of silence, I thought about putting an additional "{" where I require a "{" come as out put. So my code looked like this.

string format = string.Format("{{0:d{0}}}", mask.Length);
string formattedValue = string.Format(format, count);

To my happiness, that code worked.