Skip to content

The compiler should allow the return of a span declared and initialized by switch expression. #44588

@HobbsCode

Description

@HobbsCode

Version Used:
.netcoreapp3.1
VS 16.6.0

Steps to Reproduce:

public static ReadOnlySpan<T> GetSpan1<T>(int x)
{
    // As return statement. Works fine.

    return x switch
    {
        0 => default,
        _ => default,
    };
}

public static ReadOnlySpan<T> GetSpan2<T>(int x)
{
    // Forward declare local variable, then init. Works fine.

    ReadOnlySpan<T> span;

    span = x switch
    {
        0 => default,
        _ => default,
    };

    return span;
}

public static ReadOnlySpan<T> GetSpan3<T>(int x)
{
    // Declare and init to local variable in single statement produces compiler complaint upon return.

    ReadOnlySpan<T> span = x switch
    {
        0 => default,
        _ => default,
    };

    return span; // Compiler Complaint: "may expose referenced variables outside of their declaration scope."
}

Expected Behavior:
The compiler should allow the returning of the span in the method GetSpan3().

Actual Behavior:
The compiler complains that the return statement "may expose referenced variables outside of their declaration scope."

Metadata

Metadata

Assignees

Type

No type

Projects

No projects

Milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions