An empty Array with no elements is allocated.
Rule descriptionInitializing 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 violationsTo 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.
When to suppress warningsIt'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:
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 warningIf 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
For more information, see How to suppress code analysis warnings.
See alsoRetroSearch is an open source project built by @garambo | Open a GitHub Issue
Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo
HTML:
3.2
| Encoding:
UTF-8
| Version:
0.7.4