Skip to content

Collection initializers can leak refs #75802

@jjonescz

Description

@jjonescz

Version Used: 4.13.0-2.24555.1 (9dcb2a3)

Steps to Reproduce:

using System;
using System.Collections;
using System.Diagnostics.CodeAnalysis;

R r = M();
Console.WriteLine(r.F);

static R M()
{
    var local = 1;
    return new R() { local };
}

ref struct R : IEnumerable
{
    public ref readonly int F;

    public void Add([UnscopedRef] in int x)
    {
        F = ref x;
    }

    IEnumerator IEnumerable.GetEnumerator() => throw null;
}

Expected Behavior: Error on return new R() { local }; like there would be if explicitly written as var r = new R(); r.Add(local); return r;.

Actual Behavior: No errors. The code accesses a dead reference when executing.

Metadata

Metadata

Assignees

Type

Projects

No projects

Milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions