Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Invoke ToList() method using reflection at runtime in C#

I have a generic as follows.

public class PaginatedList<T> : List<T>
{...}

I simply want to invoke ToList() method on that object at runtime using reflection.

Can someone please help.

I have come so only far.

MethodInfo toListMethod = typeof(Enumerable).GetMethod("ToList");
var constructedToList = toListMethod.MakeGenericMethod(TypeObjectOfT);
constructedToList.Invoke(paginatedListObject, null);

I get exception at the last line with message, Parameter count mismatch. I feel that the first two steps are ok, as I have checked the toListMethod.ToString() and constructedToList.ToString(). And they have given me the following output, which I feel is correct.

System.Collections.Generic.List`1[TSource] ToList[TSource](System.Collections.Generic.IEnumerable`1[TSource])
System.Collections.Generic.List`1[AvbhHis.BL.Entities.PatientCategory] ToList[PatientCategory](System.Collections.Generic.IEnumerable`1[AvbhHis.BL.Entities.PatientCategory])

Questions: 1. Am I right so far?

  1. What should be the parameter to MakeGenericMethod() method. In my case it is the Type of intance of the object of Type T at runtime.

  2. There seems to be some problem with the Invoke method call. Is passing null correct as second parameter? The first parameter should be an object of the type PaginatedList right?

My energy is out, so kindly help.

like image 433
VivekDev Avatar asked Oct 20 '25 11:10

VivekDev


2 Answers

The first parameter [to Invoke] should be an object of the type PaginatedList right?

ToList is a static method on Enumerable that takes an IEnumerable<T> as it's only parameter:

public static List<TSource> ToList<TSource>(
    this IEnumerable<TSource> source
)

Invoke takes the instance as the first parameter and the method parameters after that. For a static method you use null for the "instance" parameter.

So the proper syntax would be

object o = constructedToList.Invoke(null, new object[] {paginatedListObject});

o will then be an object of type List<T> (but you don't know kniw what T is at compile time, so you can't cast it).

like image 189
D Stanley Avatar answered Oct 23 '25 00:10

D Stanley


List<T> has a constructor that takes an IEnumerable<T> (Which gets called in ToList) so you can simplyfy this task by writing the following:

    var resul = Activator.CreateInstance(typeof(List<>).MakeGenericType(TypeObjectOfT), paginatedListObject);
like image 44
CSharpie Avatar answered Oct 22 '25 23:10

CSharpie