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

Code analysis

CA1855: Use Span<T>.Clear() instead of Span<T>.Fill()

Learn about code analyzer rule CA1855 - Use Span.Clear() instead of Fill()

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

Cause

System.Span.Fill() is called to fill the elements of a span with a default value.

Rule description

It's more efficient to call System.Span.Clear than to call System.Span.Fill() to fill the elements of the span with a default value.

How to fix violations

Replace the call to System.Span.Fill() with a call to System.Span.Clear.

Example

The following code snippet shows a violation of CA1855:

csharp
void M(Span<byte> span)
{
    span.Fill(0);
}

The following code snippet fixes the violation:

csharp
void M(Span<byte> span)
{
    span.Clear();
}

When to suppress warnings

It's safe to suppress this warning if performance isn't a concern.

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

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

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