roslyn icon indicating copy to clipboard operation
roslyn copied to clipboard

Missing ref safety error inside `foreach`

Open AlekseyTs opened this issue 1 year ago • 0 comments

class Program
{
    static void Main()
    {
        int i0 = 0;
        S s0 = new S(ref i0);
        {
            int i1 = 1;
            for (S s1 = new S(ref i1);;) {
                s0 = s1; // 1
                break;
            }
        }
        {
            int i1 = 1;
            foreach (S s2 in Enumerable1.Create(ref i1)) {
                s0 = s2; 
                break;
            }
        }
    }
}
ref struct S
{
    public S(ref int i) { }
}

class Enumerable1
{
    public static Enumerable1 Create(ref int p) => default;
    public Enumerator1 GetEnumerator() => default;
}

class Enumerator1
{
    public S Current => throw null;
    public bool MoveNext() => false;
}

Observed:

error CS8352: Cannot use variable 's1' in this context because it may expose referenced variables outside of their declaration scope
                s0 = s1; // 1
                     ~~

Expected one more error:

error CS8352: Cannot use variable 's2' in this context because it may expose referenced variables outside of their declaration scope
                s0 = s2; 
                     ~~

AlekseyTs avatar Sep 22 '22 16:09 AlekseyTs