Question Can someone give it a try

devkeh

New member
Joined
Apr 7, 2021
Messages
3
Programming Experience
Beginner
Hello, everyone, I'm try to loop through this jagged array. When I looped through I can only access the element index.
When I tried to access the item in the array I get IndexOutOfRangeException.
Screenshot from 2021-04-07 13-41-57.png
 
As much fun as it would be to write out that code for ourselves, please post it as text, formatted as code, and avoid posting pictures of code in the future. Also, please provide a more complete explanation of the problem. I don't see where you're even trying to access the array elements so how could it be failing?
 
As much fun as it would be to write out that code for ourselves, please post it as text, formatted as code, and avoid posting pictures of code in the future. Also, please provide a more complete explanation of the problem. I don't see where you're even trying to access the array elements so how could it be failing?
Thanks for the feedback. I will do just as you suggested.
 
Hello, everyone, I'm try to loop through this jagged array. When I looped through I can only access the element index.
When I tried to access the item in the array I get IndexOutOfRangeException.

Jagged Array:
static void Main(string[] args)
{
    var d = new[]
    {
        new[,]
        {
            {4, 5}, {7, 9}, {2, 3}
        },
        new[,]
        {
            {8, 4}, {6, 7}
        }
    }
    
    for( i = 0; i < d.Lenght; i++)
    {
        for(j = 0; j < d[i].Lenght; j++)
        {
            console.write(j)  // I can get the index position of the items in the array.
            console.write(d[i][i, j]) // I get IndexOutOfRangeException error
        }
    }
}
 
Your code in post #4 doesn't even compile. How can you getting be an exception if there is nothing to run if the compilation fails?
 
Anyway, the main issue is that d[i].Length is not returning what you think it is returning. It is returning the the total number of elements in the array, as per the documentation.
Gets the total number of elements in all the dimensions of the Array.
(emphasis mine.)

You seem to be under the impression that it'll return the length for a particular dimension. For that you'll want Array.GetLength().
 
Back
Top Bottom