Search code examples
c#iteratorattributes

Should I mark my iterator with DoesNotReturnAttribute if it never "yield breaks"?


Is the use of DoesNotReturnAttribute here appropriate or not?

[DoesNotReturn]
public static IEnumerable<int> X()
{
    yield return 0;
    yield return 1;
    throw new Exception("Go away");
}

Solution

  • This returns, so no; you can see this here - the [DoesNotReturn] ends up here:

        [System.Runtime.CompilerServices.NullableContext(1)]
        [IteratorStateMachine(typeof(<X>d__0))]
        [DoesNotReturn]
        public static IEnumerable<int> X()
        {
            return new <X>d__0(-2);
        }
    
    

    where it clearly does return.

    This seems like a missing warning, honestly. You would get a warning for simpler scenarios, or if you coded this manually.