Use AsSpan or AsMemory instead of Range-based indexers for getting Span or Memory portion of an array
Use AsSpan or AsMemory instead of Range-based indexers for getting Span or Memory 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.Span1 or System.Memory`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:
Span<SomeT> slice = arr[a..b];Memory<SomeT> slice = arr[a..b];
### Does not detect
Explicit conversions:
Span<SomeT> slice = (Span<SomeT>)arr[a..b];Memory<SomeT> slice = (Memory<SomeT>)arr[a..b];
Cause
When using a range-indexer on an array and implicitly assigning the value to System.Span1 or System.Memory1.
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 AsMemory instead of the Range-based indexer on an array from the list of options that's presented. !Code fix for CA1833 - Use AsSpan or AsMemory instead of Range-based indexers for getting Span or Memory 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
Span<byte> tmp2 = arr[0..5];
Memory<byte> tmp4 = arr[5..10];
...
}
}When to suppress
It's safe to suppress a violation of this rule if creating a copy is intended.