title | description | ms.date | f1_keywords | helpviewer_keywords | dev_langs | ||||
---|---|---|---|---|---|---|---|---|---|
CA1855: Use Span.Clear() instead of Fill() |
Learn about code analyzer rule CA1855 - Use Span.Clear() instead of Fill() |
11/16/2022 |
|
|
|
Property | Value |
---|---|
Rule ID | CA1855 |
Title | Use Span<T>.Clear() instead of Span<T>.Fill() |
Category | Performance |
Fix is breaking or non-breaking | Non-breaking |
Enabled by default in .NET 8 | As suggestion |
xref:System.Span%601.Fill(%600)?displayProperty=nameWithType is called to fill the elements of a span with a default value.
It's more efficient to call xref:System.Span%601.Clear?displayProperty=nameWithType than to call xref:System.Span%601.Fill(%600)?displayProperty=nameWithType to fill the elements of the span with a default value.
Replace the call to xref:System.Span%601.Fill(%600)?displayProperty=nameWithType with a call to xref:System.Span%601.Clear?displayProperty=nameWithType.
The following code snippet shows a violation of CA1855:
void M(Span<byte> span)
{
span.Fill(0);
}
The following code snippet fixes the violation:
void M(Span<byte> span)
{
span.Clear();
}
It's safe to suppress this warning if performance isn't a concern.
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 CA1855
// The code that's violating the rule is on this line.
#pragma warning restore CA1855
To disable the rule for a file, folder, or project, set its severity to none
in the configuration file.
[*.{cs,vb}]
dotnet_diagnostic.CA1855.severity = none
For more information, see How to suppress code analysis warnings.