Simple C# output
Asked Answered
M

3

8

So I have been playing around with C# lately and I don't understand output formatting.

using System;

namespace Arrays
{
    class Program
    {
        static void Main()
        {
            Random r = new Random();

            int[] Numbers = new int[10];
            for (int i = 0; i < Numbers.Length; i++)
            {
                Numbers[i] = r.Next(101);
            }

            for (int i = 0; i < Numbers.Length; i++)
            {
                Console.WriteLine("index {0} holds number {0}", i,Numbers[i]);
            }
        }
    }
}

Output Code

My expected output was index i holds number Number[i]. So can anyone explain what to change, or link me with a good C# page on output formatting topic. I know there is a way to do it in 2 lines.

Musicianship answered 20/11, 2013 at 15:1 Comment(0)
P
19

Change

Console.WriteLine("index {0} holds number {0}", i, Numbers[i]);

to

Console.WriteLine("index {0} holds number {1}", i, Numbers[i]);

Reason: Your indices (in the format string) reference the parameters after the string in zero-based index order. So {0} for the first parameter after the string, {1} for the second, {2} if you have a third etc.

See this page for more info.

edit: You can reference the parameters multiple times in your format String, too. E.g.:

Console.WriteLine(
    "index {0} holds number {1} (Numbers[{0}] == {1})", i, Numbers[i]);

This also is equivalent to

Console.WriteLine(String.Format(
    "index {0} holds number {1} (Numbers[{0}] == {1})", i, Numbers[i]));
Pasol answered 20/11, 2013 at 15:2 Comment(2)
Oh, weird... Thought the {0} was a placeholder for numbers, like %d in java.Musicianship
@destroyergm No, actually the String.Format function will automatically call ToString() on each of the parameters. So the type is irrelevant. edit: although the type could implement IFormattable for some special format strings. But still, the order of parameters determines their index.Pasol
K
5

Your second print is wrong. You use string.Format but you don't bind the second parameter.

It should be:

Console.WriteLine( "index {0} holds number {1}", i, Numbers[i] );
Kelleher answered 20/11, 2013 at 15:4 Comment(0)
R
5
Console.WriteLine("index {0} holds number {1}", i, Numbers[i] );
Ruthven answered 20/11, 2013 at 15:4 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.