Dynamically pass Type to Method<T>

I've a method , that retrieves to me some data according to some type I passed in parameter, like this :

    protected void FillList<TEntity>()
    {
        doWorkForTEntity();
    }

I Need to dynamically call this method :

            Type[] entities = System.Reflection.Assembly.GetAssembly(typeof(User)).GetTypes();
            Type currentEntity = (from entity in entities
                                  where entity.Name.Equals(this.targetEntity)
                                  select entity).FirstOrDefault();
            FillList<currentEntity>();

I got this error :

The type or namespace name 'currentEntity' could not be found (are you missing a using directive or an assembly reference?)

I've tried an intermediate object type, no success

Any Idea please ?

Answers


Since there is no information about entity type in compile time, you need to construct and call appropriate method by reflection:

Type[] entities = System.Reflection.Assembly.GetAssembly(typeof(User)).GetTypes();
Type currentEntity = (from entity in entities
                      where entity.Name.Equals(this.targetEntity)
                      select entity).FirstOrDefault();     
var method = this.GetType().GetMethod("FillList",  BindingFlags.Instance | BindingFlags.NonPublic)
                           .MakeGenericMethod(currentEntity);
method.Invoke(this, new object[0]);

Need Your Help

How to embedd nested response using JSON?

json node.js

I wanted to send following response message using JSON. How to achieve this ? Do I need to define nested objects ?