Câu hỏi phỏng vấn C#
Câu hỏi

What is jagged array in C# and when to prefer...

Câu trả lời

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[1].

To declare and initialize a jagged array in C#, you can use the following syntax:

csharp Copy
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#:

csharp Copy
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);
    for (int j = 0; j < jaggedArray[i].Length; j++)
    {
        Console.Write(jaggedArray[i][j] + " ");
    }
    Console.WriteLine();
}

Output:

Copy
Row 0: 1 2 3 
Row 1: 4 5 
Row 2: 6 7 8 9

You should prefer jagged arrays over multi-dimensional arrays when:

  1. The size of each row in your data is variable and unpredictable. Jagged arrays allow you to allocate each row with a different size, making them more memory-efficient[1][3].

  2. You need to add or remove rows frequently. Jagged arrays provide more flexibility in resizing indiv...

expert

expert

Gợi ý câu hỏi phỏng vấn

senior

Why to use lock statement in C#?

senior

What is the best practice to have best performance using Lazy objects?

junior

What you understand by Value types and Reference types in .NET? Provide some comparison

Bình luận

Chưa có bình luận nào

Chưa có bình luận nào