Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing a Type to a generic method at runtime [duplicate]

I have something like this

Type MyType = Type.GetType(FromSomewhereElse);

var listS = context.GetList<MyType>().ToList();

I would like to get the Type which is MyType in this case and pass it to the Generic Type method GetList

This is the error I am getting:

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

like image 430
devendar r mandala Avatar asked May 22 '13 18:05

devendar r mandala


People also ask

Is it possible to inherit from a generic type?

An attribute cannot inherit from a generic class, nor can a generic class inherit from an attribute.

Is generic code faster or slower than non generic code?

cmd/compile: generic functions are significantly slower than identical non-generic functions in some cases #50182.

Can we overload generic methods?

A generic method can also be overloaded by nongeneric methods. When the compiler encounters a method call, it searches for the method declaration that best matches the method name and the argument types specified in the call—an error occurs if two or more overloaded methods both could be considered best ...

Can a generic class have multiple constraints?

Multiple interface constraints can be specified. The constraining interface can also be generic.


2 Answers

You can use reflection and construct your call like this:

Type MyType = Type.GetType(FromSomewhereElse);

var typeOfContext = context.GetType();

var method = typeOfContext.GetMethod("GetList");

var genericMethod = method.MakeGenericMethod(MyType);

genericMethod.Invoke(context, null);

Note that calling methods with reflection will add a huge performance penalty, try to redesign your solution if possible.

like image 56
Alexander Avatar answered Oct 01 '22 14:10

Alexander


You'll have to use reflection:

var method = context.GetType()
    .GetMethod("GetList").MakeGenericMethod(MyType)

IEnumerable result = (IEnumerable)method.Invoke(context, new object[0]);
List<object> listS = result.Cast<object>().ToList();

However there's no way to use your type instance MyType as a static type variable, so the best you can do is to type the results as object.

like image 27
Lee Avatar answered Oct 01 '22 14:10

Lee