dotnet/roslyn

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

Opened this issue · 1 comments

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."

https://github.com/dotnet/csharplang/blob/main/proposals/csharp-12.0/collection-expressions.md#ref-safety

It looks like the spec supports what Jan is saying, it is defined to have safe-context caller-context.

It looks like a similar error occurs when Add signature is public void Add(int x) { }. SharpLab.