Search code examples
c#.netgenericsgeneric-method

Can I use a type from reflection as a type parameter?


Can I use a type from reflection as a type parameter? E.g. I want to pick a persister based on a passed object:

IPersister GetPersisterFor(IEntity entity)
{
    return GetPersisterFor<entity.GetType()>(); // <-- this cannot be compiled
}

IPersister GetPersisterFor<TEntity>() where TEntity : IEntity
{
    //some logic to get persister...
}

Solution

  • Only via reflection; you would need to use GetMethod to get the MethodInfo for the generic method, then call MakeGenericMethod(entity.GetType()).Invoke(this, null); on that.

    However, easier is to cheat via dynamic:

    IPersister Evil<T>(T obj) where T : IEntity {
        return GetPersisterFor<T>();
    }
    

    And make the first method just:

    return Evil((dynamic)entity);
    

    This is then a dynamic expression which will detect the correct T to use (to call Evil-of-T) for you.

    Note: the only reason you need an extra method is to make sure it doesn't resolve back to itself recursively, since the names are the same.