Yield keyword can not be used in ref struct?

Viewed 406

I would like to use yield in ref structure method:

public ref struct RefStruct 
{
    public IEnumerator<int> GetEnumerator()
    {
        yield return 1;
    }
}

The compiler complains about the error:

CS4013 Instance of type 'RefStruct' cannot be used inside a nested function, query expression, iterator block or async method

But the instance of RefStruct is not used in the iterator block.

I can assume that yield translation rules have not changed for ref structures. As in classes, method with yield is translated into GetEnumerator class, which has field that stores an instance of ref struct. This is incorrect since the class field cannot be ref struct. But in this case, the compiler must complain about another error.

Is this a bug or am I doing something wrong?

1 Answers

I don't know what's going on, but after some playing around I found the following work around, maybe it is useful

public ref struct RefStruct 
{
    public IEnumerator<int> GetEnumerator()
    {
        return Foo();

        IEnumerator<int> Foo()
        {
            yield return 1;
        }
    }
}
Related