Robert Daraż
Robert Daraż

Reputation: 323

Formatting strings in C#

I'm trying to format array elements to look like a table with some columns to have right alignment and some left as shown in Composite Formatting article (or What is the optional argument in C# interpolated string for?)

Why I'm getting FormatException on call to Console.WriteLine?

Here is sample that demonstrates this:

using System;
namespace ConsoleApplication97
{
    class Program
    {
        public struct User
        {
            public string Name;
            public byte Age;
        }
        static void Main(string[] args)
        {
            User[] Bar = new User[2];
            Bar[0].Name = "Jan Kowalski";
            Bar[0].Age = 32;
            Bar[1].Name = "Piotr Nowak";
            Bar[1].Age = 56;
            for (int i = 0; i < Bar.Length; i++)
            {
                Console.WriteLine("{0 , -15} | { 1,  5}", Bar[i].Name, Bar[i].Age);
            }
            Console.ReadLine();
        }
    }
}

Value "Name" should be on the left side (alignment -15), "Age" should be on the right side (alignment 5).

Upvotes: 3

Views: 158

Answers (1)

D Stanley
D Stanley

Reputation: 152624

Interesting - the formatter seems to be picky about excess whitespace in format strings. This worked for me:

Console.WriteLine("{0, -15} | {1, 5}", Bar[i].Name, Bar[i].Age);

Upvotes: 9

Related Questions