Composite Formatting in .NET
Friday, March 18, 2011
I’ve been looking for this particular link on MSDN for a while. In short, it tells you how to combine alignment, padding, and formatting simultaneously while formatting data.
Of course, we’ve all used String.Format before, as in:
Console.WriteLine(string.Format("Line {0}: {1}",
linenumber, line));
Now I’m always searching for a quick way to make the colons line up in the output. I know a can add a format specifier after the index, like so:
Console.WriteLine(string.Format("Line {0:D3}: {1}",
linenumber, line));
This will format the line number as if we used linenumber.ToString(“D3″). But formatting numbers is cumbersome. D3 will always prepend zeroes, which looks ugly. I can specify “###”, but that won’t fill up to three positions. “0##” will do that, but (again) always prepend zeroes. Now I could start writing expressions to pad the output of ToString() but there’s an easier way: composite formatting.
I know you can line up strings in your output, padding either left or right, but always forget how. Here’s how:
Console.WriteLine(string.Format("Line {0,3}: {1}",
linenumber, line));
By specifying a comma and a width in the format string. {0,3} will align right (= pad left), {0,-3} will align left (= pad right). Now here’s the trick: you can combine formatting and padding by specifying both:
Console.WriteLine(string.Format("Line {0,3:x2}: {1}",
linenumber, line));
This will format the line number as a two-digit hexadecimal number, and left-pad it to three positions. (For line numbers that doesn’t make any sense, but you get the point). Of course, {0,-3:x2} will right-pad the line number. The link on MSDN mentioned above explains this in a little more detail.
Test it out yourself using our brand new Online .NET Format Tester!