AnaRoyal
AnaRoyal

Reputation: 3

Index was outside the bounds of the array with jagged array c#

i want to try jagged arrays but i got an index out range exception , any help ?

class Program
    {
        static void Main(string[] args)
        {

            int[][] jaggedarr = new int[1][];


  jaggedarr[0] = new int[0];


            jaggedarr[0][0] = 25;

            Console.WriteLine(jaggedarr[0][0]);
            Console.ReadKey();
        }
    }

Upvotes: 0

Views: 274

Answers (2)

Jack J Jun- MSFT
Jack J Jun- MSFT

Reputation: 5986

We can define the jagged arrays as the following code without exception.

 static void Main(string[] args)
        {
            int[][] jaggedarr = new int[1][];
            jaggedarr[0] = new int[0];
            jaggedarr[0] = new int[] { 25};
            Console.WriteLine(jaggedarr[0][0]);
            Console.ReadKey();
        }

Result:

enter image description here

Upvotes: 0

JonasH
JonasH

Reputation: 36596

jaggedarr[0] = new int[0];

this creates a list with zero size. You want a list of size 1.

Upvotes: 1

Related Questions