CA1825: Avoid zero-length array allocations

Value
Rule ID CA1825
Category Performance
Fix is breaking or non-breaking Non-breaking

Cause

An empty Array with no elements is allocated.

Rule description

Initializing a zero-length array leads to an unnecessary memory allocation. Instead, use the statically allocated empty array instance by calling the Array.Empty method. The memory allocation is shared across all invocations of this method.

How to fix violations

To fix a violation, replace the zero-length array allocation with a call to Array.Empty. For example, the following two code snippets show a violation of the rule and how to fix it:

class C
{
    public void M1()
    {
        // Violates rule CA1825.
        var a = new int[0];
    }
}
class C
{
    public void M1()
    {
        // Resolves rule CA1825 violation.
        var a = System.Array.Empty<int>();
    }
}

Tip

A code fix is available for this rule in Visual Studio. To use it, position the cursor on the array allocation and press Ctrl+. (period). Choose Use Array.Empty from the list of options that's presented.

Code fix for CA1825 - use array empty

When to suppress warnings

It's safe to suppress a violation of this rule if you're not concerned about the additional memory allocation.

Note

You might see false positive warnings from this rule if all of the following apply:

  • You're using Visual Studio 2022 version 17.5 or later with an older version of the .NET SDK, that is, .NET 6 or earlier.
  • You're using the analyzers from the .NET 6 SDK or an older version of the analyzer packages, such as Microsoft.CodeAnalysis.FxCopAnalyzers.
  • You're using a zero-length array as an attribute argument, most commonly as a params parameter.

The false positives are due to a breaking change in the C# compiler. Consider using a newer analyzer that contains the fix for the false positive warnings. Upgrade to Microsoft.CodeAnalysis.NetAnalyzers version 7.0.0-preview1.22464.1 or newer or use the analyzers from the .NET 7 SDK.

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 CA1825
// The code that's violating the rule is on this line.
#pragma warning restore CA1825

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

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

To disable this entire category of rules, set the severity for the category to none in the configuration file.

[*.{cs,vb}]
dotnet_analyzer_diagnostic.category-Performance.severity = none

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

See also