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);
}
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.
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());
}
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);
}
}
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");
}