Skip to content

[API Proposal]: {ReadOnly}Span(ref T) constructor #67445

@stephentoub

Description

@stephentoub

Background and motivation

As part of the C# 11 work to enable ref fields, it will be safe to create a {ReadOnly}Span from a ref (with an implicit length of 1), because the compiler will track the lifetime of the ref and ensure the created span can't outlive it. Creating spans for a single item is quite common, and we should have public constructors for this situation.

This has been proposed by others offline... I agree with it and am just opening the issue for it so we can make forward progress on it.
cc: @jaredpar, @AaronRobinsonMSFT, @tannergooding

API Proposal

namespace System
{
    public ref struct Span<T>
    {
+        public Span(ref T reference);
    }

    public ref struct ReadOnlySpan<T>
    {
+        public ReadOnlySpan(in T reference);
    }
}

API Usage

int i = ...;
CallMethodThatTakesASpan(new ReadOnlySpan<T>(in i));

Alternative Designs

No response

Risks

No response

Metadata

Metadata

Assignees

Labels

Type

No type

Projects

No projects

Milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions