Редагувати

Поділитися через


CA1814: Prefer jagged arrays over multidimensional

Property Value
Rule ID CA1814
Title Prefer jagged arrays over multidimensional
Category Performance
Fix is breaking or non-breaking Breaking
Enabled by default in .NET 9 No

Cause

A member is declared as a multidimensional array, which can result in wasted space for some data sets.

Rule description

In a multidimensional array, each element in each dimension has the same, fixed size as the other elements in that dimension. In a jagged array, which is an array of arrays, each inner array can be of a different size. By only using the space that's needed for a given array, no space is wasted. This rule, CA1814, recommends switching to a jagged array to conserve memory.

How to fix violations

To fix a violation of this rule, change the multidimensional array to a jagged array.

When to suppress warnings

It's okay to suppress a warning from this rule if the multidimensional array does not waste space.

Suppress a warning

If you just want to suppress a single violation, add preprocessor directives to your source file to disable and then re-enable the rule.

#pragma warning disable CA1814
// The code that's violating the rule is on this line.
#pragma warning restore CA1814

To disable the rule for a file, folder, or project, set its severity to none in the configuration file.

[*.{cs,vb}]
dotnet_diagnostic.CA1814.severity = none

For more information, see How to suppress code analysis warnings.

Example

The following example shows declarations for jagged and multidimensional arrays.

Imports System

Public Class ArrayHolder
    Private jaggedArray As Integer()() =  {New Integer() {1, 2, 3, 4}, _
                                           New Integer() {5, 6, 7}, _
                                           New Integer() {8}, _
                                           New Integer() {9}}
    
    Private multiDimArray As Integer(,) =  {{1, 2, 3, 4}, _
                                            {5, 6, 7, 0}, _
                                            {8, 0, 0, 0}, _
                                            {9, 0, 0, 0}}
End Class
public class ArrayHolder
{
    int[][] jaggedArray = { new int[] {1,2,3,4},
                            new int[] {5,6,7},
                            new int[] {8},
                            new int[] {9}
                          };

    int[,] multiDimArray = {{1,2,3,4},
                             {5,6,7,0},
                             {8,0,0,0},
                             {9,0,0,0}
                            };
}