Skip to content

Unexpected ref safety error reported when a collection expression is used to construct a ref struct with Add method #76374

Open
@jjonescz

Description

@jjonescz

Version Used: main 2024-12-10

Steps to Reproduce:

using System.Collections;
class C
{
    R M()
    {
        var local = 1;
        return [local]; // error CS9203: A collection expression of type 'R' cannot be used in this context because it may be exposed outside of the current scope.
    }
}
ref struct R : IEnumerable
{
    public void Add(in int x) { }
    IEnumerator IEnumerable.GetEnumerator() => throw null;
}

Expected Behavior: Compiles successfully, the in int x parameter of the Add method cannot be captured into the ref struct. Replacing the collection expression with a collection initializer new() { local }; also works fine. So does making the struct a non-ref struct. See also #76237 (comment).

Actual Behavior: Error is reported: "CS9203: A collection expression of type 'R' cannot be used in this context because it may be exposed outside of the current scope."

Metadata

Metadata

Assignees

No one assigned

    Type

    Projects

    No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions