In my C# Console program I have 4 variables. Their names and types are as follows:
int ID
bool Status
bool Available
int Count
I would like to be able to print them to the Console, nicely indented as follows:
However, when I use the tabs "\t", to format my string, it does not take into account the text width, and all the values are indented waywardly as follows:
How do I fix this? I don't want to use any third party libraries, but simply .NET functionality such as String.Format().
You can pad them with spaces like this:
Console.WriteLine("{0,-10}\t{1,-5}\t{2,-5}\t{3,-10}", ID, Status, Available, Count);
And if you want to right-align them instead:
Console.WriteLine("{0,10}\t{1,5}\t{2,5}\t{3,10}", ID, Status, Available, Count);
I set the padding to the longest possible length of an integer or boolean represented in string form. You may have to adjust it to account for your column titles.
Try a padding
var data = new string[5,4]
{
{ "ID", "Status", "Available", "Count" },
{ "------", "------", "------", "------" },
{ "1123", "True", "False", "-1" },
{ "23", "False", "True", "-23" },
{ "3", "True", "True", "-1" }
};
for (int i = 0; i < data.GetLength(0); i++)
{
Console.WriteLine("{0,-10}\t{1,-10}\t{2,-10}\t{3,-10}", data[i, 0], data[i, 1], data[i, 2], data[i, 3]);
}