C#idiomatic C#
ca1825fundamentals/code-analysis/quality-rules

Code analysis

CA1825: Avoid zero-length array allocations

Learn about code analysis rule CA1825: Avoid zero-length array allocations

CA1825 Performance enabled by default in .NET 10: As suggestion
Fix is breaking or non-breaking Non-breakingApplicable languages C# and Visual Basic

Cause

An empty System.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 System.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 System.Array.Empty. For example, the following two code snippets show a violation of the rule and how to fix it:

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

When to suppress warnings

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

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.

csharp
#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.

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

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

See also