Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does an IEnumerator have to have at least one yield statement, even if it's unreachable?

Why does this code:

public IEnumerator Test()
{
}

Gives you an error:

Error CS0161 'Test.GetEnumerator()': not all code paths return a value

However this code:

public IEnumerator Test()
{
    if(false)
        yield return 0;
}

Doesn't? (and works as expected; first MoveNext() returns false)

When using IEnumerators as coroutines, sometimes you want to make a coroutine (IEnumerator) that doesn't have an async operations yet (is not yielding anything) but might do that in future.

like image 918
splattru Avatar asked Jan 01 '26 00:01

splattru


1 Answers

From C# specification:

A block that contains one or more yield statements (§8.14) is called an iterator block. Iterator blocks are used to implement function members as iterators (§10.14).

So if you have one or more yield statements, no matter reachable or not, your method is iterator (under the hood that will generate iterator class). But if you don't have any yield statements your method is the ordinal method (not an iterator) which has a return value of IEnumerable type. As any other method which returns some value, you must either return value of required type or throw an exception from method body. Same rules are applied when you have method which returns string or int value.

like image 184
Sergey Berezovskiy Avatar answered Jan 02 '26 13:01

Sergey Berezovskiy