Search code examples
genericscastingyieldreturn-type

Returning generic parameter T with yield return


I want to generate a list of types (which is inherited from class T) from a loaded dll file. But when I use the following code, application becomes frozen/stuck:

static IEnumerable<T> GetAllTypes<T>(string dllName)
{
    Assembly plugin = Assembly.LoadFrom(dllName);
    if (plugin != null)
    {
        Type[] types = plugin.GetTypes();
        foreach (var type in types)
        {
            if (type.IsClass && type.IsSubclassOf(typeof(T)))
            {
                Console.WriteLine(type.Name);
                yield return (T)(Object)type;
            }
        }
    }
    else
        throw new InvalidDataException();
}

However, if I do not use the yield return, everything works as expected and no freezing occurs . Can anyone explain this behavior?

static void GetAllTypes<T>(string dllName)
{
    Assembly plugin = Assembly.LoadFrom(dllName);
    if (plugin != null)
    {
        Type[] types = plugin.GetTypes();
        foreach (var type in types)
        {
            if (type.IsClass && type.IsSubclassOf(typeof(T)))
            {
                Console.WriteLine(type.Name);
                //yield return (T)(Object)type;
            }
        }
    }
    else
        throw new InvalidDataException();
}

Solution

  • Note that type is an instance of System.Type. You should just (yield) return it, and make IEnumerable<System.Type> the return type.

    Your type cast code tries to convert that object to an instance of T which is invalid and impossible, it can't ever work. An object of type T is not the same as the Type T itself, but that is what your code is trying to force.

    Not sure if a 'hang' could be the result but the casting code is just wrong.