Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 529
Robert Daraż Avatar asked May 13 '26 08:05

Robert Daraż


1 Answers

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);
like image 173
D Stanley Avatar answered May 15 '26 21:05

D Stanley



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!