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.

3 Answers 3

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

2 Comments

Oh, weird... Thought the {0} was a placeholder for numbers, like %d in java.
@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.
5
Console.WriteLine("index {0} holds number {1}", i, Numbers[i] );

Comments

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] );

Comments

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.