Scott
Scott

Reputation: 281

Call generic method and to call method on return type

How would I go about calling a generic method only knowing the type at runtime and also to then call a method on the type returned? I have a looked at a lot of examples but can't seem to get it working.

This is what I have so far.

public interface IDataMapper<TEntity> where TEntity : IEntity
{
    void Update(TEntity entity);
}

public IDataMapper<TEntity> GetMapper<TEntity>() where TEntity : IEntity
{
    // Return something of type IDataMapper<TEntity>
}

foreach (IEntity entity in _dirtyObjects)
{
    MethodInfo method = typeof(MapperFactory).GetMethod("GetMapper");
    MethodInfo generic = method.MakeGenericMethod(entity.GetType());

    generic.Invoke(_mapperFactory, null);
    // I now want to call the Update() method
    // I have tried to cast to IDataMapper<IEntity> which results in a null ref ex
}

Thanks for any advice.

Upvotes: 2

Views: 116

Answers (1)

Reed Copsey
Reed Copsey

Reputation: 564861

You have to keep working with reflection:

object dataMapper = generic.Invoke(_mapperFactory, null);
method = dataMapper.GetType().GetMethod("Update");
method.Invoke(dataMapper, new object[] {entity});

Upvotes: 4

Related Questions