3

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).

0

1 Answer 1

9

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);
Sign up to request clarification or add additional context in comments.

2 Comments

Saw it also: Console.WriteLine("{0 , -15} | { 1, 5}", Bar[i].Name, Bar[i].Age);
It appears that anything that supports Composite Formatting, such as Console.WriteLine and string.Format, have this whitespace issue where they give a FormatException if there's spaces after any opening bracket { (it seems to support spaces anywhere else, however). But note that string interpolation doesn't have this issue: Console.WriteLine($"{ Bar[i].Name, -15} | { Bar[i].Age, 5}"); works fine for me.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.