Search code examples
.netienumerabledeferred-execution

Check if return type is IEnumerable<T>


How can I check if the return type of a function is IEnumerable<T>? In other words, I don't want to match List<T>, even though it implements IEnumerable<T>. Or put even another way, how can I detect if a function has deferred execution?


Solution

  • I assume you are interacting with a MethodInfo?

    Type returnType = methodInfo.ReturnType;
    bool isEnumerable = returnType.IsGenericType && 
                        returnType.GetGenericTypeDefinition() == typeof(IEnumerable<>);
    

    Of course, just because it returns IEnumerable doesn't mean it uses deferred execution (i.e. yield return) and there's no real way to check for that without decompiling the code.