What is jagged array in C# and when to prefer jagged arrays over multi-dimensional arrays?
What is jagged array in C# and when to prefer jagged arrays over multi-dimensional arrays?
A jagged array in C# is an array of arrays where each element can hold an array of different sizes. Unlike regular multi-dimensional arrays, jagged arrays allow for flexible and uneven lengths, making them ideal for storing complex data structures like tables or matrices with varying row lengths.
To declare and initialize a jagged array in C#, you can use the following syntax:
int[][] jaggedArray = new int[][]
{
new int[] { 4, 6, 8 },
new int[] { 1, 0, 2, 4, 6 }
};
Here's a practical example of using a jagged array in C#:
int[][] jaggedArray = new int[][]
{
new int[] { 1, 2, 3 },
new int[] { 4, 5 },
new int[] { 6, 7, 8, 9 }
};
for (int i = 0; i < jaggedArray.Length; i++)
{
Console.Write("Row {0}: ", i);
Đăng nhập để tham gia thảo luận cùng mọi người.
Chưa có bình luận nào
Hãy là người đầu tiên chia sẻ suy nghĩ của bạn.