Home >Backend Development >C++ >C# Multidimensional Arrays: When to Use `[][]` (Jagged) vs `[,]` (Uniform)?

C# Multidimensional Arrays: When to Use `[][]` (Jagged) vs `[,]` (Uniform)?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2025-01-24 11:32:09469browse

C# Multidimensional Arrays: When to Use `[][]` (Jagged) vs `[,]` (Uniform)?

Multidimensional array [][] and [,]

in C#

C# provides two types of multidimensional arrays: jagged arrays ([][]) and uniform arrays ([,]).

Jagged array

Jagged arrays are arrays of arrays. This means that each element in the jagged array is an array of values, and these value arrays can be of different lengths.

Uniform array

A uniform array is an array with a fixed number of dimensions and a fixed size for each dimension.

Example

The following code creates a jagged array:

<code class="language-csharp">double[][] ServicePoint = new double[10][];</code>

The above code creates an array of 10 elements, where each element is a reference to an array of double-precision floating point numbers. The size of each internal array can be different.

Error in option 1

The following code will produce a syntax error:

<code class="language-csharp">double[][] ServicePoint = new double[10][9];</code>

This error occurs because the size of the internal array is specified when the array is created, which is not allowed for jagged arrays. The correct way to create a jagged array is to specify only the size of the outer array and then allocate the size to each inner array separately.

Assign values ​​to uniform array rows

The following code will generate an error:

<code class="language-csharp">double[,] ServicePoint = new double[10, 9];

double[] d = new double[9];
ServicePoint[0] = d;</code>

This error occurs because the entire array cannot be assigned to a unified array. Each element must be assigned a value. To assign a value to a single element, the row and column index must be specified:

<code class="language-csharp">ServicePoint[0, 0] = d[0];
ServicePoint[0, 1] = d[1];
// ... //</code>

The above is the detailed content of C# Multidimensional Arrays: When to Use `[][]` (Jagged) vs `[,]` (Uniform)?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn