Search code examples
c#.netstringformatting

Format Strings in Console.WriteLine method


Im new to C# programming. Can someone please explain the following code:

Console.WriteLine( "{0}{1,10}", "Face", "Frequency" ); //Headings
Console.WriteLine( "{0,4}{1,10}",someval,anotherval);

I understand that this prints two columns of values with the headings given, and {0} refers to the first argument given. But what is the meaning of the format strings of the form {x,y} ?


Solution

  • 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∙∙∙∙∙∙∙]