Hidden C# feature - string.Format Width

If you had written console applications before, you most probably would have spent quite an amount of time formatting the output with Console.Write(“some string”). Its pretty cumbersome to type “\t” or add couple of space “   “ in order to neatly present the output.

Well you don’t need to worry much with C#. It has a method called Format which easily allows to change the format of the string. A HelloWorld example for string.Format would be:

string.Format("Hello {0}", "Prabir");

That’s something most of you already know. But there is more cool feature than to just add a number inside the curly braces - {no}.

One could even add a comma and another number – minimum width to it.

string.Format("Price: {0,5}",price);

The above code would right align the price with width of 5. (If you want to left align you could use a negative number.)

Console.WriteLine("Product: {0,-7} Price: {1,5}", product1, price1);
Console.WriteLine("Product: {0,-7} Price: {1,5}", product2, price2);

The above sample would produce the following output. Notice the negative (-) sign for Product? Its left aligned, while the price is positive signed and is right aligned.

image

string.Format-width.zip (11.30 kb)


blog comments powered by Disqus