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
 

jmcilhinney

C# Forum Moderator
Staff member
Joined
Apr 23, 2011
Messages
3,720
Location
Sydney, Australia
Programming Experience
10+
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?
 

devkeh

New member
Joined
Apr 7, 2021
Messages
3
Programming Experience
Beginner
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.
 

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.

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
        }
    }
}
 

Skydiver

Staff member
Joined
Apr 6, 2019
Messages
2,892
Location
Chesapeake, VA
Programming Experience
10+
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?
 

Skydiver

Staff member
Joined
Apr 6, 2019
Messages
2,892
Location
Chesapeake, VA
Programming Experience
10+
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().
 
Top Bottom