Add parameters for padding a string (C#)

Viewed 113

{0,N} formatting pads a string to the left with spaces. For example:

string [] names = { "A", "Bob", "Charles" };
Console.WriteLine("{0}{0,15}", names[0]);
Console.WriteLine("{0}{0,13}", names[1]);
Console.WriteLine("{0}{0,10}", names[2]);

Which results in lines with a total length of 16 characters:

A                A
Bob            Bob
Charles    Charles

You can achieve the same thing with String.PadLeft, for example:

foreach (var name in names)
{
    Console.WriteLine("{0}{1}", name, name.PadLeft(16-name.Length, ' '));
}

This attempt to add a parameter to {0,N} formatting compiles, but throws an exception at runtime:

foreach (var name in names)
{
    Console.WriteLine("{0}{0,16-name.Length}", name);
}

Is it possible to pass a parameter into {0,N} style formatting?

1 Answers

You can use string interpolation and double the braces for the format pattern:

string[] names = { "A", "Bob", "Charles" };

int paddingMax = 16;

foreach (string name in names)
  Console.WriteLine($"{{0}}{{0,{paddingMax - name.Length}}}", name);

Output:

A              A
Bob          Bob
Charles  Charles

To check for outbreaks:

foreach ( string name in names )
{
  int padding = paddingMax - name.Length;
  if ( padding < 0 )
    Console.WriteLine("Padding error for: " + name);
  else
    Console.WriteLine($"{{0}}{{0,{padding}}}", name);
Related