Use AsSpan or AsMemory instead of Range-based indexers for getting ReadOnlySpan or ReadOnlyMemory portion of an array
Use AsSpan or AsMemory instead of Range-based indexers for getting ReadOnlySpan or ReadOnlyMemory portion of an array
Microsoft docsDescription
The range indexer on a System.Span1 is a non-copying System.Span1.Slice operation. But for the range indexer on an array, the method System.Runtime.CompilerServices.RuntimeHelpers.GetSubArray will be used instead of System.Span1.Slice, which produces a copy of the requested portion of the array. This copy is usually unnecessary when it's implicitly used as a System.ReadOnlySpan1 or System.ReadOnlyMemory`1 value. If a copy isn't intended, use the System.MemoryExtensions.AsSpan or System.MemoryExtensions.AsMemory method to avoid the unnecessary copy. If the copy is intended, either assign it to a local variable first or add an explicit cast.
The analyzer only reports when an implicit cast is used on the result of the range indexer operation.
### Detects
Implicit conversions:
ReadOnlySpan<SomeT> slice = arr[a..b];ReadOnlyMemory<SomeT> slice = arr[a..b];
### Does not detect
Explicit conversions:
ReadOnlySpan<SomeT> slice = (ReadOnlySpan<SomeT>)arr[a..b];ReadOnlyMemory<SomeT> slice = (ReadOnlyMemory<SomeT>)arr[a..b];
Cause
When using a range-indexer on an array and implicitly assigning the value to System.ReadOnlySpan1 or System.ReadOnlyMemory1.
How to fix violations
To fix a violation of this rule, use the System.MemoryExtensions.AsSpan or System.MemoryExtensions.AsMemory extension method to avoid creating unnecessary data copies. A code fix is available for this rule in Visual Studio. To use it, position the cursor on the violation and press <kbd>Ctrl</kbd>+<kbd>.</kbd> (period). Choose Use AsSpan instead of the Range-based indexer on an array from the list of options that's presented. !Code fix for CA1832 - Use AsSpan or AsMemory instead of Range-based indexers for getting ReadOnlySpan or ReadOnlyMemory portion of an array
You can also avoid this warning by adding an explicit cast.
Example
class C
{
public void TestMethod(byte[] arr)
{
// The violation occurs for both statements below
ReadOnlySpan<byte> tmp1 = arr[0..2];
ReadOnlyMemory<byte> tmp3 = arr[5..8];
...
}
}When to suppress
It's safe to suppress a violation of this rule if creating a copy is intended.