Avoid zero-length array allocations
Use `Array.Empty<T>()` instead of allocating an empty array.
Microsoft docsDescription
Allocating a new zero-length array is wasteful; Array.Empty<T>() returns a cached singleton.
Cause
An empty System.Array with no elements is allocated.
Why it matters
Reusing the cached empty array avoids needless allocations on hot paths.
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: A code fix is available for this rule in Visual Studio. To use it, position the cursor on the array allocation and press <kbd>Ctrl</kbd>+<kbd>.</kbd> (period). Choose Use Array.Empty from the list of options that's presented. !Code fix for CA1825 - use array empty
Examples
return new int[0];return Array.Empty<int>();When to suppress
It's safe to suppress a violation of this rule if you're not concerned about the additional memory allocation. 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
paramsparameter.
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.