Sobes.tech
Middle

Is it possible to determine externally whether a method is implemented via yield or via List?

sobes.tech AI

Answer from AI

Externally, that is, when calling the method, it is not possible to directly determine whether it is implemented using yield (iterator) or returns a ready List.

The reason is that both options return IEnumerable<T> or a similar interface, and for the calling code, this is the same contract.

However, you can indirectly understand the behavior:

  • If the method returns IEnumerable<T> and uses yield, then elements will be generated as they are iterated over (lazy execution).
  • If it returns a List<T>, then the collection is already fully formed.

To check, you can measure the time or behavior during partial iteration:

var result = SomeMethod();
var enumerator = result.GetEnumerator();
if (enumerator.MoveNext()) {
    // If the method uses yield, execution will start here
}

But this does not guarantee 100% accuracy, as the method may return IEnumerable<T> from an already prepared collection.

In summary: without analyzing the source code or using reflection/debugging, it is impossible to determine this precisely.

Is it possible to determine externally whether a… - sobes.tech