Im new to C# programming. Can someone please explain the following code:
Console.WriteLine( \"{0}{1,10}\", \"Face\", \"Frequency\" ); //Headings
Console.Writ
This is a padding value...if the argument isn't the length that is specified, it puts spaces in.
E.g. if you had {0,10} and the argument for {0} was "Blah", the actual value printed would be "Blah<SPACE><SPACE><SPACE><SPACE><SPACE><SPACE>"
...Blah, with 6 extra spaces to make up a string of 10 length
ps - not sure how to put actual spaces in...need to look up SO faq no doubt
When you see {x,y}
, x
represents the argument's index and y
the alignment, as specified here. The complete syntax is the following:
{index[,alignment][:formatString]}
It adds padding to the left. Very useful for remembering the various string formatting patterns is the following cheat sheet:
.NET String.Format Cheat Sheet
Positive values add padding to the left, negative add padding to the right
Sample Generates String.Format("[{0, 10}]", "Foo"); [∙∙∙∙∙∙∙Foo] String.Format("[{0, 5}]", "Foo"); [∙∙Foo] String.Format("[{0, -5}]", "Foo"); [Foo∙∙] String.Format("[{0, -10}]", "Foo"); [Foo∙∙∙∙∙∙∙]