Edit

CA1517: Use ReadOnlySpan<T> or ReadOnlyMemory<T> instead of Span<T> or Memory<T>

Property Value
Rule ID CA1517
Title Use ReadOnlySpan<T> or ReadOnlyMemory<T> instead of Span<T> or Memory<T>
Category Maintainability
Fix is breaking or non-breaking Non-breaking
Enabled by default in .NET 10 No
Enabled by default in .NET 11 As suggestion
Applicable languages C#

Cause

A method has a Span<T> or Memory<T> parameter that it doesn't modify.

Rule description

Use ReadOnlySpan<T> or ReadOnlyMemory<T> for data that a method only reads. The read-only type makes the method's intent clear and lets callers pass data that they can't modify.

How to fix violations

Change the parameter type to its read-only counterpart. The analyzer doesn't report methods that can't safely change their parameter type, such as virtual or interface methods.

Examples

The following code shows a violation of CA1517:

static int GetFirst(Span<int> values) => values[0];

Change Span<T> to ReadOnlySpan<T>:

static int GetFirst(ReadOnlySpan<int> values) => values[0];

For Memory<T> parameters, use ReadOnlyMemory<T> instead.

When to suppress warnings

Suppress the warning only when the method must expose a writable parameter, even though its current implementation doesn't modify the data.

Suppress a warning

To suppress a single violation, add preprocessor directives to your source file to disable and then re-enable the rule.

#pragma warning disable CA1517
// The code that's violating the rule is on this line.
#pragma warning restore CA1517

To disable the rule for a file, folder, or project, set its severity to none in the configuration file.

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

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

See also