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.

dev-cyprium
  • 526
  • 1
  • 6
  • 17

3 Answers3

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]));
David S.
  • 5,523
  • 1
  • 34
  • 68
  • Oh, weird... Thought the {0} was a placeholder for numbers, like %d in java. – dev-cyprium Nov 20 '13 at 15:12
  • 1
    @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. – David S. Nov 20 '13 at 15:13
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] );
zkanoca
  • 8,468
  • 8
  • 42
  • 87
Ghost93
  • 165
  • 1
  • 2
  • 12
5
Console.WriteLine("index {0} holds number {1}", i, Numbers[i] );
zkanoca
  • 8,468
  • 8
  • 42
  • 87