Skip to content

ReadOnlySpan and Span must be readonly structs. #23452

@VSadov

Description

@VSadov

ReadOnlySpan and Span do not have any mutable fields and should be readonly just from the principle of least privilege.

Also, being not readonly makes the code like the following an error:

            Span<int> stackAllocated = stackalloc int[100];
            Span<int> returnableSpan = new int[100];

            // error, compiler thinks that CopyTo could just do 'this = other'
            // there would be no danger if Span<T> was `readonly`
            returnableSpan.CopyTo(stackAllocated);

Also see: dotnet/roslyn#21911

For now I can assume that ReadOnlySpan and Span will be readonly and specialcase them to be readonly regardless of annotations.
That would fix dotnet/roslyn#21911 temporarily.

Depending on the compiler used they should be either

public readonly ref struct Span<T> { ... }

or

[S.R.CS.ReadOnlyAttribute]
[S.R.CS.IsByRefLikeAttribute]
public struct Span<T> { ... }

Metadata

Metadata

Assignees

Type

No type

Projects

No projects

Milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions