0

I'm new to C# and looking at arrays.

Given:

int[][] myJagArray = new int[5][];

Why does the following print the types of j (System.Int32[]), and not each j's contents?

foreach (int[] j in myJagArray)
{
    Console.WriteLine("j : {0}",j);
}

5 Answers 5

5

Because Array.ToString() does not return the contents of the array, it returns the type name, and Console.WriteLine implicitly calls ToString() on each object you send it as a parameter.

This has no regard to the fact that the array is part of a multi-dimensional array, it is simply the way the CLR developers chose to (or rather, chose not to) implement ToString() on System.Array.

Sign up to request clarification or add additional context in comments.

Comments

1

It prints the output from ToString() method, since j, in this case, is an array, it use Object ToString implementation, and that behavior is printing its type.

Here what you may want to do:

foreach (int[] j in myJagArray)
{
    StringBuilder sb = new StringBuilder("j : ");

    foreach (int k in j)
    {
        sb.append("[").append(k).append("]");
    }

    Console.WriteLine(sb.Tostring());
}

Comments

1

You're printing out an array of int.

Try the following to print the first value within the array:

Console.WriteLine("j : {0}",j[0]);

To print out the entire contents you may want to try the following:

foreach (int[] j in myJagArray)
{
    foreach (int i in j)
    {
        Console.WriteLine("i : {0}",i);
    }
}

Comments

0

You should do like below

for(int i=0;i<5;i++)
    for( int j=0;j<5;j++)
        print(myjagarray[i][j].tostring());

Comments

0

When you output a value using Console.WriteLine you are actually first calling ToString() on that value, and Array.ToString() doesn't return the values, but the type. If you want to output the values of j you need to run a second loop:

foreach (int[] j in myJagArray)
{
    Console.Write("j: ");
    foreach (int i in j)
    {
        Console.Write("{0} ",i);
    }    
    Console.Write("\n");
}

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.