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?
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.
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.
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).
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With