0

I Have the full name of a type as string and I would like to use this string to tell type of a generic method. see this

      string typeStr ="Dll.NameSpace.MyType";
      var list = new List<Dll.NameSpace.MyType>();//should put typeStr here
      var result = call.SomeGenericMethod<...>(obj);//should put typeStr here

This answer didn't help me. If you try visiting this other one, it does not satisfy my needs.

EDITS: The generic method I'm trying to call is an extension one. I have unsuccessfully tried the following code, method remains null

     var result = repo.Get();
     Type elementType = 
             Type.GetType("x2o_Care.Models.ViewModels.PatientViewModel");
     MethodInfo method =typeof(AutoMapper.QueryableExtensions.Extensions) 
                      .GetMethod("ProjectTo", new[] { typeof(IQueryable)});
        MethodInfo generic = method.MakeGenericMethod(elementType);

        var model = generic.Invoke(result.OrderBy(e => true).Take(20), null);
Bellash
  • 7,560
  • 6
  • 53
  • 86
  • 2
    The second link has precisely what you need for the last line. What you have on the second line is not possible, because `var` needs the exact type at compile time. – Sergey Kalinichenko Sep 07 '17 at 13:44
  • Then, is this what you're looking for? [How to call a generic extension method with reflection?](https://stackoverflow.com/q/15927028)? If not, can you provide a [mcve] for your problem? – dbc Sep 08 '17 at 05:47

1 Answers1

0

Your code is exactly what you need. You just need to specify exactly what overload of ProjectTo method you need as there are a few. Make sure to specify all the parameters in GetMethod/

For example:

MethodInfo method =typeof(AutoMapper.QueryableExtensions.Extensions) 
                      .GetMethod("ProjectTo", new[] { typeof(IQueryable),
                          typeof(object), 
                          typeof(Expression<Func<TDestination, object>>[]) 
                        });

Here is a list of all the ProjectTo methods: https://github.com/AutoMapper/AutoMapper/blob/master/src/AutoMapper/QueryableExtensions/Extensions.cs

Boris Modylevsky
  • 3,029
  • 1
  • 26
  • 42