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

middle

Explain assignment vs shallow copy vs deep copy for a Record in C#

senior

What is scope of a Protected Internal member variable of a C# class?

expert

You have defined a destructor in a class that you have developed by using the C#, but the destructor
never executed. Why?

Bình luận

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

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